gpt4 book ai didi

java - 如何在java中删除带有特殊字符的单词边界字符串

转载 作者:行者123 更新时间:2023-12-02 01:41:53 25 4
gpt4 key购买 nike

我正在尝试使用replaceAll api从句子中删除子字符串。

Ex: String str = "Condition (Where Clause) Address Line1 Collectable (%)"
str = str.replaceAll("Condition \\(Where Clause\\)","");

这工作正常,但如果字符串类似于 Condition (Where Clause)xyz 那么它也会删除 Condition (Where Clause) 并且生成的字符串将具有 xyz。我只想替换精确匹配。为此,我尝试使用 \b 但它末尾有特殊的 char ) 。因此, \\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|$) 。我正在寻找其他更好的解决方案。

最佳答案

根据您的解释,一些可能的测试用例:

"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"

如果您只想准确删除“条件(Where 子句)”,除非它后面直接跟有空格或字符串末尾以外的内容,您可以使用以下内容:

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"

关于java - 如何在java中删除带有特殊字符的单词边界字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54366190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com