以给定模式开头时的递归匹配 [英] Recursive matching when preceded by a given pattern

查看:34
本文介绍了以给定模式开头时的递归匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下两个字符串:

a (b (c) d) e
f (g (h) i) j

我想递归匹配括号中的内容.我可以使用以下模式来做到这一点:

I would like to match the content in parentheses recursively. I can do so by using the following pattern:

\((?>[^()]|(?R))*\)

这将匹配 (b (c) d)(g (h) i).

现在,假设我想递归匹配括号中的内容,仅当前面有字母 a 时.我怎样才能做到这一点?

Now, let's say I want to match recursively the content in parentheses only when preceded by the letter a. How can I do that?

使用 (?<=a\s)\((?>[^()]|(?R))*\) 似乎不起作用.

Using (?<=a\s)\((?>[^()]|(?R))*\) does not seem to work.

推荐答案

你可以重复创建一个捕获组并重复第一个子模式,而不是重复整个模式:

Instead of repeating the whole pattern, you could repeat create a capturing group and repeat the first sub pattern instead:

(?<=a\s)(\((?>[^()]|(?1))*\))

  • (?<=a\s) 断言左边是 a 和一个空格字符
  • ( 捕获组 1
    • \( 匹配(
    • (?> 原子组
      • [^()] 匹配除 () 之外的任何字符(使用 [^()]+> 以提高效率)
      • |
      • (?1) 递归第一个子模式
        • (?<=a\s) Assert what is on the left is a and a whitespace char
        • ( Capture group 1
          • \( Match (
          • (?> Atomic group
            • [^()] Match any char except ( or ) (Use [^()]+ to make it more efficient)
            • | Or
            • (?1) Recurse the first subpattern
            • 正则表达式演示

              添加捕获组时,我们可以省略lookbehind并匹配a和一个空格字符:

              When adding a capturing group, we can omit the lookbehind and match a and a whitespace char:

              a\s(\((?>[^()]|(?1))*\))
              

              正则表达式演示

              这篇关于以给定模式开头时的递归匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆