如何使用正则表达式递归匹配模式? [英] How can I recursively match a pattern using Regular Expressions?
本文介绍了如何使用正则表达式递归匹配模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
字符串可以是以下之一:
The string can be like one of the following:
a(b,c)
a(a(b,c),d)
a(a(a(a(a(b,c),d),a(e,f)),g),h)
etc
我想匹配无限数量的a(x,y)。我怎么能用Regex做到这一点?这就是我所拥有的:
I want to match an unlimited number of "a(x,y)". How can I do that using Regex? Here's what I have:
\\w\\(((?:\\([a-zA-Z0-9]+\\))|(?:[a-zA-Z0-9]+)),((?:\\([a-zA-Z0-9]+\\))|(?:[a-zA-Z0-9]+))\\)
它只匹配两个a(x,y)的递归。
It only matches up two recursions of "a(x,y)".
推荐答案
Java的标准正则表达式lib不支持递归,因此你无法将这些通用嵌套结构与它匹配。
Java's standard regex lib does not support recursion, so you can't match such general nested constructs with it.
但是支持递归的风格(Perl,PCRE,.NET等)你可以使用如下表达式:
But in flavors that do support recursion (Perl, PCRE, .NET, etc) you can use expressions like:
\w+(?:\((?R)(?:,(?R))*\))?
这篇关于如何使用正则表达式递归匹配模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文