php 正则 多个大括号,什么正则表达式将捕获大括号/括号内的多个实例?

如果您可以使用alternate regex module,那么可以使用单个正则表达式执行此操作。但它很复杂且难以理解。但它正确处理悬挂支撑。

regex模块支持访问所有捕获组的之前匹配,这对于以下工作至关重要:

>>> import regex

>>> # The regex behavior version seems to make no difference in this case, so both '(?V0)...' and '(?V1)...' will work.

>>> pattern = r'(?V0)[{] (?P\s+)? (?: (?: [^\s}]+ (?P\s+) )* [^\s}]+ (?P\s+)? )? [}]'

>>> string = 'abc and 123 {foo-bar bar baz } bit {yummi tummie} byte.'

>>> [s for m in regex.finditer(pattern, string, regex.VERBOSE) for s in m.captures('u')]

[' ', ' ', ' ', ' ']

简单地说,这个正则表达式找到'{' blanks? ((nonblanks blanks)* nonblanks blanks?)? '}'形式的匹配项,并将所有空白部分分配给名为u((?P...))的同一个捕获组。

它也适用于包含不匹配的{和}:的字符串

>>> # Even works with dangling braces:

>>> badstring = '}oo} { ab a b}} xy {xy x y}cd {{ cd } e{e }f{ f} { }{} }{'

>>> # Fully flattened result:

>>> [s for m in regex.finditer(pattern, badstring, regex.VERBOSE) for s in m.captures('u')]

[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

>>> # Less flattened (e.g. for verification):

>>> [v for m in regex.finditer(pattern, badstring, regex.VERBOSE) for v in m.capturesdict().values()]

[[' ', ' ', ' '], [' ', ' '], [' ', ' '], [' '], [' '], [' '], []]

在Python 3.5.1 x64,regex 2016.3.2上测试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值