【问题标题】:Java String.replaceAll regexJava String.replaceAll 正则表达式
【发布时间】:2010-04-08 17:35:10
【问题描述】:

我想替换

的第一个上下文

web/style/clients.html

使用 java String.replaceFirst 方法,我可以得到:

${pageContext.request.contextPath}/style/clients.html

我试过了

String test =  "web/style/clients.html".replaceFirst("^.*?/", "hello/");

这给了我:

你好/style/clients.html

但是当我这样做时

 String test =  "web/style/clients.html".replaceFirst("^.*?/", "${pageContext.request.contextPath}/");

给我

java.lang.IllegalArgumentException:非法组引用

【问题讨论】:

    标签: java regex replace


    【解决方案1】:

    我的预感是它正在爆炸,因为 $ 是一个特殊字符。来自the documentation

    注意反斜杠 () 和美元 替换字符串中的符号 ($) 可能会导致结果不同 比如果它被视为 文字替换字符串。美元 标志可被视为参考 如所述捕获的子序列 上面,反斜杠用于 转义文字中的字符 替换字符串。

    所以我相信你会需要类似的东西

    "\\${pageContext.request.contextPath}/"
    

    【讨论】:

      【解决方案2】:

      已经有一种方法可以转义替换Matcher.quoteReplacement()中的所有特殊字符:

      String test =  "web/style/clients.html".replaceFirst("^.*?/", Matcher.quoteReplacement("${pageContext.request.contextPath}/"));
      

      【讨论】:

        【解决方案3】:

        String test = "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");

        应该可以解决问题。 $ 用于正则表达式中的反向引用

        【讨论】:

          【解决方案4】:

          $ 是一个特殊字符,你必须转义它。

          String test =  "web/style/clients.html".replaceFirst("^.*?/", "\\${pageContext.request.contextPath}/");
          

          【讨论】:

            猜你喜欢
            • 2011-04-25
            • 2013-05-27
            • 2023-03-10
            • 1970-01-01
            • 2015-12-29
            • 1970-01-01
            • 2016-09-28
            • 2013-01-18
            相关资源
            最近更新 更多