gpt4 book ai didi

java - replaceFirst ArrayOutOfBoundsException 异常

转载 作者:行者123 更新时间:2023-11-29 06:37:00 25 4
gpt4 key购买 nike

我在使用 replaceFirst 时得到一个奇怪的 ArrayOutOfBoundsException:

"this is an example string".replaceFirst("(^this )", "$1\\") // throws ArrayOutOfBoundsException
"this is an example string".replaceFirst("(^this )", "$1") // works fine

我正在努力实现这个字符串:

"this \is an example string"

如果我尝试在替换字符串中放入转义的反斜杠,为什么会出现 ArrayOutOfBoundsException?这在 Android 上正在发生,如果它有所作为的话

这是一个 ideone异常示例。

这是 logcat 异常堆栈跟踪:

java.lang.ArrayIndexOutOfBoundsException: index=14 at java.util.regex.Matcher.appendEvaluated(Matcher.java:149) at java.util.regex.Matcher.appendReplacement(Matcher.java:111) at java.util.regex.Matcher.replaceFirst(Matcher.java:304) at java.lang.String.replaceFirst(String.java:1793)

最佳答案

你需要使用这个正则表达式:-

"this is an example string".replaceFirst("(^this )", "$1\\\\");

因为 \ 需要双重转义。因此,对于每个 \,您将需要 4 个\(最初您需要 2 个 \,因此请提供此信息,以备不时之需稍后更改)。

引用 this answer 中的几行:-

The second argument isn't a regex-string, but a regex-replacement-string, in which the backslash also has a special meaning (it is used to escape the special character $ used for variable interpolation and is also used to escape itself)

关于java - replaceFirst ArrayOutOfBoundsException 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19114322/

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