【问题标题】:Nested Lookarounds in java regexjava正则表达式中的嵌套环视
【发布时间】:2012-02-01 22:29:53
【问题描述】:

我有一个使用环视来确保捕获的字符串位于其他两个字符串之间的模式

换句话说就是主题字符串

xxxcabyyy

我的正则表达式看起来像

String myregex = ((?<=xxx)cab(?=[y]+))

所以我想多次使用这个正则表达式,因为我可能正在寻找其他类似的东西

(test string) xxxcabyyy

我想要一个类似于

的正则表达式
"\(test string\)(?=" + myregex + ")"

说在我的正则表达式匹配之前找到“(测试字符串)”。

这似乎并不完全正确,我认为这是因为我在我的正则表达式中有环顾四周,我现在将其嵌入到前瞻中......我能做些什么来纠正这种情况?

【问题讨论】:

    标签: java regex lookaround


    【解决方案1】:

    可以将环视放在其他环视中,但我不明白为什么需要这样做。事实上,我认为没有必要进行环视期。这不行吗?

    "\\(test string\\)\s*xxx(cab)y+"
    

    假设它是您感兴趣的cab 部分,您可以通过Matcher#group(1) 提取它。

    【讨论】:

      【解决方案2】:

      您的猜测是正确的 - 这不会起作用,因为您已经在字符串 myregex 中指定了后向和前瞻结构。解决此问题的一种方法是为您想要的后向和前瞻结构保存单独的字符串,并在您需要进行匹配之前使用它们来构建最终的正则表达式字符串。例如,您可以编写如下方法,根据lookbehind 和lookahead 结构以及它们之间的匹配内容,该方法将返回一个正则表达式字符串:

      public static String lookaroundRegex(String behind, String match, String ahead) {
          return "((?<=" + behind + ")" + match + "(?=" + ahead + "))";
      }
      

      然后您可以按如下方式使用它:

      String behind = "xxx";
      String ahead = "[y]+";
      String match = "cab";
      
      // For the first case:
      Pattern regexPattern1 = Pattern.compile(lookaroundRegex(behind, match, ahead));
      
      // For the second case:
      String behind2 = "\\(test string\\) " + behind;
      Pattern regexPattern2 = Pattern.compile(lookaroundRegex(behind2, match, ahead));
      

      【讨论】:

        【解决方案3】:

        如果您想要其他环视中的环视解决方案,您可以这样做

        \(test string\)(?=.*?((?<=xxx)cab(?=[y]+)))
        

        或者如果它是 (test string) 后跟 xxxcabyyy 和 只是空格 在你之后:

        \(test string\)(?= *((?<=xxx)cab(?=[y]+)))
        

        这是因为在您匹配 (test string) 时,在您点击 xxxcabyyy 之前仍有字符要走,您必须将它们包含在您的前瞻中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-18
          • 1970-01-01
          • 1970-01-01
          • 2016-08-24
          相关资源
          最近更新 更多