How can I recursively match a pattern using Regular Expressions?

后端 未结 5 1792
小蘑菇
小蘑菇 2020-12-04 01:36

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

相关标签:
5条回答
  • 2020-12-04 02:06

    I think you are looking for something like:

    a(x,y) = [a-z] ( [a-z] , [a-z] )

    regex = a(x,y) | a(regex|y) | a(x, regex)

    Not sure how you can do in a language.

    0 讨论(0)
  • 2020-12-04 02:09

    2 options - 1) Use Lexical Analysis to do the pattern matching & replacement on your own [OR] 2) If you want to stick to Regex then use some shell programming (or any supporting language) & call it from Java.

    0 讨论(0)
  • 2020-12-04 02:12

    Java's standard regex lib does not support recursion, so you can't match such general nested constructs with it.

    But in flavors that do support recursion (Perl, PCRE, .NET, etc) you can use expressions like:

    \w+(?:\((?R)(?:,(?R))*\))?
    
    0 讨论(0)
  • 2020-12-04 02:16

    The language you're describing isn't a regular language so it can't be matched by a regular expression. Look into lexical analysis (i.e. use a parser)

    0 讨论(0)
  • 2020-12-04 02:26

    You can also use my Regular Expression library https://github.com/florianingerl/com.florianingerl.util.regex , that supports Recursive Regular Expressions! The API is basically the same as the one of java.util.regex, just the required import statements are different, e.g.

    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();
    
    0 讨论(0)
提交回复
热议问题