我正在尝试使用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
,因为它也可以在行尾。
我正在考虑像Condition \\(Where Clause\\)(\b|\s|$)
这样使用。我正在寻找其他更好的解决方案。
答案 0 :(得分:1)
我认为以下内容就足够
str.replaceAll("(\\s|^)Condition \\(Where Clause\\)(\\s|$)","")
答案 1 :(得分:1)
根据您的解释一些可能的测试用例:
"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)"
,除非直接在其后跟空格或String的末尾,否则可以使用以下方法:
str.replaceAll("(^|\\s)Condition \\(Where Clause\\)(\\s|$)", "$1$2")
这将保留任何前导或尾随空格,因此上面的最后一个测试用例变为" "
。
如果您还想删除这些前导空格,那么最后一个测试用例将变成空的字符串""
,则可以删除上面的$1$2
。
这将导致(每个测试用例的第一行保留空格,另一行删除它们):
Try it online来查看实际效果。
"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"