Is there any regular expression api or library for java that can accept multiple groups with the same name in one pattern?
Asked
Active
Viewed 4,471 times
7
-
5Why? How would you access each group? – tckmn Dec 21 '13 at 22:44
-
4@DoorknobofSnow OP is probably trying to achieve something like `context1(?
regex)context2|context3(? – Pshemo Dec 21 '13 at 22:54otherRegex)context4`? In this case there will be only one group with name `name` in match. -
Can you give an example of what you're trying to match? – Szymon Dec 21 '13 at 23:14
-
>(ab(?[\w]*)|bs(?[\w]*)) – AIA Dec 22 '13 at 00:53
-
like above example sometime just one name will be filled and sometimes it is possible to have more than one filled same-name so the best one or the last one should be chosen by regex engine. – AIA Dec 22 '13 at 01:04
2 Answers
4
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

bblue
- 545
- 5
- 24
1
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.

Ahosan Karim Asik
- 3,219
- 1
- 18
- 27