【问题标题】:replaceFirst ArrayOutOfBoundsExceptionreplaceFirst ArrayOutOfBoundsException
【发布时间】:2013-10-01 10:52:28
【问题描述】:

我在使用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 在 java.util.regex.Matcher.appendEvaluated(Matcher.java:149) 在 java.util.regex.Matcher.appendReplacement(Matcher.java:111) 在 java.util.regex.Matcher.replaceFirst(Matcher.java:304) 在 java.lang.String.replaceFirst(String.java:1793)

【问题讨论】:

    标签: java regex replace


    【解决方案1】:

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

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

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

    引用this answer的几行:-

    第二个参数不是一个正则表达式字符串,而是一个 regex-replacement-string,其中反斜杠也有一个特殊的 含义(用于转义特殊字符 $ 用于 变量插值,也用于自身转义)

    【讨论】:

    • All:替换肯定不是正则表达式,那为什么需要双转义呢?
    • @RGraham - 检查我提供的答案链接。它解释了双转义反斜杠的原因。
    【解决方案2】:
    "this is an example string".replaceFirst("(^this )", "$1\\")
    

    在上面的代码中,\\实际上只是一个\(第一个反斜杠用于转义第二个反斜杠,因为字符串中的反斜杠用于转义其他内容,本身并不意味着什么)。

    但是!在正则表达式中,单个反斜杠本身用于转义目的,因此需要再次转义。因此,如果您需要在 Java 中的正则表达式 String 中使用文字反斜杠,则需要编写四个反斜杠 "\\\\"

    【讨论】:

      【解决方案3】:

      尝试:

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

      输出:

      this \is an example string
      

      String 上的replaceFirstreplaceAll 一样的函数执行正则表达式,您必须首先转义\,因为它是文字(产生\\),然后因为正则表达式(产生\\\\)。

      【讨论】:

      • 抱歉,我更新了我的问题。我只需要在结果字符串中使用一个反斜杠
      【解决方案4】:

      你需要:

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

      因为正则表达式需要双重转义。

      PS: 尽管替换字符串不是真正的正则表达式,但由于使用了 $1$2 等分组变量,它仍然由正则表达式引擎处理,因此需要双精度逃跑。

      **相反,如果您想避免使用正则表达式,则只需使用Sring#replace(String n, String r):

      "this is an example string".replace("this ", "this \\")
      

      显然这里不涉及正则表达式,因此只需一次转义就足够了。

      【讨论】:

        猜你喜欢
        • 2016-02-08
        • 2013-08-07
        • 2016-07-23
        • 1970-01-01
        • 2017-05-14
        • 2015-05-07
        • 2017-11-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多