multiple groups with the same name regex java?

4.9k views Asked by At

Is there any regular expression api or library for java that can accept multiple groups with the same name in one pattern?

2

There are 2 answers

0
bblue On

This is a very old question, but google brought me here, I found a solution for PHP using the /J modifier. All details explained here: http://www.rexegg.com/regex-capture.html#dupe_names

In .NET, PCRE (C, PHP, R…), Perl and Ruby, you can use the same group name at various places in your pattern. (In PCRE you need to use the (?J) modifier or PCRE_DUPNAMES option.) In these engines, this regex would be valid:

:(?<token>\d+)|(?<token>\d+)#

Working example here https://regex101.com/r/h7HJXj/1

0
Ahosan Karim Asik On

alternative of (ab(?<a>[\w]*)|bs(?<a>[\w]*)) regex is (ab|bs)(?<a>[\w]*) with same name. check test in the demo link with (ab(?<a>[\w]*)|bs(?<b>[\w]*)) and (ab|bs)(?<a>[\w]*) . these gives you same result.

demo