正则表达式,lookbehind / lookahead with“。*”

时间:2013-11-07 11:12:00

标签: java regex

必须与其背后的空间一起使用 这样的也必须采取 如果单词就像\ gloss {word},\(这里有什么)sezione {word},\ gloss {any word 任何东西),\(这里有什么)sezione {任何单词任何东西},都不能被采取。
如果里面的单词就像\(除了光泽或sezione之外的任何东西){单词}和\ {除了光泽或sezione之外的任何内容){strings word 必须采取它 显然,aword,worda和aworda不得采取。

粗体字已被拍摄,字没有)

我没有抓住“{.... word .....}”

中的单词

到目前为止,我的猜测是(?<!(sezione\{)|(gloss\{))(\b)( ?)word(\b)(?!.*\{}),我会在lookbehind和lookahead((?<!(sezione\{)|(gloss\{).*)[...])上添加“。*”,但是这样就会停止工作。

如果这件事,我打算使用Java的正则表达式引擎

提前致谢

编辑:主要问题是

  

\(这里有什么)sezione {任何任何事情}

如果我不能得到这个,这应该解决整个问题

1 个答案:

答案 0 :(得分:1)

让我们为您的用例设置一些简单的事实:

  1. Java(和大多数)正则表达式引擎不支持可变长度的lookbehind
  2. Java正则表达式引擎不支持允许您重置搜索的\K模式
  3. 如果没有,您需要使用解决方法,分三个步骤:

    1. 确保输入符合预期lookbehind pattern
    2. 如果确实如此,则按lookbehind pattern
    3. 删除匹配的字符串
    4. 在替换的String匹配中并提取搜索模式
    5. 请考虑以下代码:

      String str = "(anything here)sezione{anything word anything}";
      // look behind pattern
      String lookbehind = "^.*?(?:sezione|gloss|word)\\{";
      // make sure input is matching lookbehind pattern first
      if (str.matches(lookbehind + ".*$")) {
              // actual search pattern
          Pattern p = Pattern.compile("[^}]*?\\b(word)\\b");
              // search in replaced String
          Matcher m = p.matcher(str.replaceFirst(lookbehind, ""));
          if (m.find())
              System.out.println(m.group(1));
              //> word
      }
      

      PS:您可能需要通过检查搜索模式起点的输入字符串中的索引来改进代码。

相关问题