简体   繁体   English

如何使用正则表达式递归匹配模式?

[英]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

I want to match an unlimited number of "a(x,y)".我想匹配无限数量的“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]+))\\)

It only matches up two recursions of "a(x,y)".它只匹配“a(x,y)”的两个递归。

Java's standard regex lib does not support recursion, so you can't match such general nested constructs with it. Java 的标准正则表达式库不支持递归,因此您无法将这种通用嵌套结构与它匹配。

But in flavors that do support recursion (Perl, PCRE, .NET, etc) you can use expressions like:但在支持递归的风格(Perl、PCRE、.NET 等)中,您可以使用如下表达式:

\w+(?:\((?R)(?:,(?R))*\))?

You can also use my Regular Expression library https://github.com/florianingerl/com.florianingerl.util.regex , that supports Recursive Regular Expressions!您还可以使用我的正则表达式库https://github.com/florianingerl/com.florianingerl.util.regex ,它支持递归正则表达式! The API is basically the same as the one of java.util.regex, just the required import statements are different, eg API 与 java.util.regex 的 API 基本相同,只是需要的 import 语句不同,例如

Pattern p = Pattern.compile("(?<first>a\\((?<second>(?'first')|[a-zA-Z]),(?'second')\\))");
assert p.matcher("a(a(a(a(a(b,c),d),a(e,f)),g),h)").find();

2 个选项 - 1) 使用词法分析自己进行模式匹配和替换 [OR] 2) 如果你想坚持使用正则表达式,那么使用一些 shell 编程(或任何支持语言)并从 Java 中调用它。

The language you're describing isn't a regular language so it can't be matched by a regular expression.您描述的语言不是正则语言,因此无法通过正则表达式匹配。 Look into lexical analysis (ie use a parser)查看词法分析(即使用解析器)

I think you are looking for something like:我认为您正在寻找类似的东西:

a(x,y) = [az] ( [az] , [az] ) a(x,y) = [az] ( [az] , [az] )

regex = a(x,y) |正则表达式 = a(x,y) | a(regex|y) | a(正则表达式|y) | a(x, regex) a(x, 正则表达式)

Not sure how you can do in a language.不知道你怎么能用一种语言做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM