【问题标题】:Replace word using java regex but not quotes使用 java 正则表达式替换单词但不使用引号
【发布时间】:2016-10-14 11:00:52
【问题描述】:

我想用 java regex replace 替换句子中的一个单词。

测试字符串是a_b a__b a_bced adbe a_bc_d 'abcd' ''abcd''

如果我想替换所有以 a & 以 d 开头的单词。 我正在使用String.replaceAll("(?i)\\ba[a-zA-Z0-9_.]*d\\b","temp")

替换为a_b a__b temp adbe a_bc_d 'temp' ''temp''

如果我不想考虑引号中的字符串,我的正则表达式应该是什么?

我用String.replaceAll("[^'](?i)\\ba[a-zA-Z0-9_.]*d\\b[^']","temp") 将其替换为a_b a__btempadbe temp'abcd' ''abcd''。 它删除了那个单词的一个空格。 有没有办法只替换不在引号内的那个字符串?

PS:这个String.replaceAll("[^'](?i)\\ba[a-zA-Z0-9_.]*d\\b[^']"," temp ") 有一个解决方法。但在某些情况下它会失败。

如果我想替换句子中的一个单词,我的正则表达式应该是什么,并且我不应该考虑侧引号中的字符串。? 提前谢谢...!!!

【问题讨论】:

    标签: java regex string replace replaceall


    【解决方案1】:

    您可以使用环视断言:

    string = string.replaceAll("(?i)(?<!')\\ba[a-zA-Z0-9_.]*d\\b(?!')", "temp");
    

    RegEx Demo

    Read more about lookarounds

    【讨论】:

      【解决方案2】:

      测试目标前后是否有引号是一种错误的方法,因为您无法知道所描述的引号是开引号还是闭引号。 (尝试在测试字符串的开头添加一个引号并测试一个简单的模式,你会看到:'inside'a_outside_d'inside'

      知道引号内还是外引号的唯一方法是从开头检查字符串(或从结尾检查,但如果引号不平衡,它不太方便并且最终容易出错)。为此,您必须在目标之前描述所有可能的子字符串,例如:

      \G([^a']*+(?:'[^']*'[^a']*|\Ba+[^a']*|a(?!\w*d\b)[^a']*)*+)\ba\w*d\b
      

      详情:

      \G  # matches the start of the string or the position after the previous match
      (
          [^a']*+ # all that isn't an "a" or a quote
          (?:
              '[^']*'     [^a']* # content between quotes
            |
              \Ba+        [^a']* # "a" not at the start of a word
            |
              a(?!\w*d\b) [^a']* # "a" at the start of a word that doesn't end with "d"
          )*+
      ) # all that can be before the target in a capture group
      \ba\w*d\b # the target
      

      不要忘记在 java 字符串中转义反斜杠:\ => \\

      要进行替换,需要参考捕获组1:

      $1temp
      

      注意:要处理引号之间的转义引号,请将'[^']*' 更改为:
      '[^\\']*+(?s:\\.[^\\']*)*+'

      Demo:点击 Java 按钮。

      【讨论】:

        猜你喜欢
        • 2018-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-12
        • 1970-01-01
        • 1970-01-01
        • 2015-03-13
        • 1970-01-01
        相关资源
        最近更新 更多