我正在尝试使用 replaceAll api 从句子中删除子字符串。
Ex: String str = "Condition (Where Clause) Address Line1 Collectable (%)"
str = str.replaceAll("Condition \\(Where Clause\\)","");
这工作正常,但如果 String 是一样的,Condition (Where Clause)xyz
那么它也会删除Condition (Where Clause)
并且结果字符串将具有xyz
. 我只想替换完全匹配。为此,我正在尝试,\b
但最后有特殊字符)
。所以,\\bCondition \\(Where Clause\\)\\b
不工作。
Ex: String str = "Condition (Where Clause) Address Line1 Collectable (%)"
str = str.replaceAll("\\bCondition \\(Where Clause\\)\\b","");
由于特殊字符,这不起作用。如何删除完全匹配。我必须只删除可以有特殊字符的精确匹配。
我也尝试过使用正则表达式Pattern
,但结果相同。
更新:
我不能使用,\s
因为它也可以在行尾。我正在考虑使用 like Condition \\(Where Clause\\)(\b|\s|$)
。我正在寻找任何其他更好的解决方案。
根据您的解释,一些可能的测试用例:
"Condition (Where Clause) Address Line1 Collectable (%)"
"Condition (Where Clause)xyz"
"xyzCondition (Where Clause)"
"At the end: Condition (Where Clause)"
" Condition (Where Clause) "
"xyzCondition (Where Clause)xyz"
"In Condition (Where Clause) Between"
如果您只想"Condition (Where Clause)"
完全删除,除非它直接后跟空格或字符串末尾以外的其他内容,则可以使用以下命令:
str.replaceAll("(^|\\s)Condition \\(Where Clause\\)(\\s|$)", "$1$2")
这将保留任何前导或尾随空格,因此上面的最后一个测试用例变为" "
.
如果你还想去掉那些前导空格,让最后一个测试用例变成一个空的 String ""
,你可以去掉$1$2
上面的。
这将导致(每个测试用例的第一行保留空格,另一行删除它们):
在线试用以查看其实际效果。
"Condition (Where Clause) Address Line1 Collectable (%)" → " Address Line1 Collectable (%)"
"Condition (Where Clause) Address Line1 Collectable (%)" → "Address Line1 Collectable (%)"
"Condition (Where Clause)xyz" → "Condition (Where Clause)xyz"
"Condition (Where Clause)xyz" → "Condition (Where Clause)xyz"
"xyzCondition (Where Clause)" → "xyzCondition (Where Clause)"
"xyzCondition (Where Clause)" → "xyzCondition (Where Clause)"
"At the end: Condition (Where Clause)" → "At the end: "
"At the end: Condition (Where Clause)" → "At the end:"
" Condition (Where Clause) " → " "
" Condition (Where Clause) " → ""
"xyzCondition (Where Clause)xyz" → "xyzCondition (Where Clause)xyz"
"xyzCondition (Where Clause)xyz" → "xyzCondition (Where Clause)xyz"
"In Condition (Where Clause) Between" → "In Between"
"In Condition (Where Clause) Between" → "InBetween"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句