gpt4 book ai didi

java - Matcher.replaceAll - 在 $,\in replacement String 上阻塞

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:47:54 25 4
gpt4 key购买 nike

所以我遇到了一个很好的边缘情况,如果替换字符串中有 $ 或\,则对字符串执行 replaceAll 会阻塞。

为什么替换字符串不只是替换为与我指定的正则表达式匹配的替换?我对这里的正则表达式有什么不理解的地方?

引自 Oracle Java 7 Documentation :

public String replaceAll(String replacement)

Replaces every subsequence of the input sequence that matches the pattern with the given replacement string.

This method first resets this matcher. It then scans the input sequence looking for matches of the pattern. Characters that are not part of any match are appended directly to the result string; each match is replaced in the result by the replacement string. The replacement string may contain references to captured subsequences as in the appendReplacement method.

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

最佳答案

美元符号是一个特殊字符;你必须逃避它:

"\\$"

请注意双反斜杠 - 这就是您在 java 中编写单个反斜杠的方式,这意味着 \$ 被传递给 replace 方法。

美元符号表示对捕获组的反向引用:

"$1" // replace with group 1
"$2" // replace with group 2

还有一个特殊的第零组:

"$0" // replace with the entire match

关于java - Matcher.replaceAll - 在 $,\in replacement String 上阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16943048/

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