Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex reuse a pattern to capture multiple groups?

Tags:

java

regex

I would like to match some pattern multiple times, exactly like described here.

^(somelongpattern[0-9])([,; ]+(?1))*$

This will match for example:

somelongpattern0
somelongpattern9 ,; somelongpattern2

However above code works in pcre, it does not work not in java. It gives me an error "unclosed options group" on (?1)

Is there any way how to do this? I have a very long regex pattern and i don't want to repeat it 2 times if possible.

like image 453
Lopfest Avatar asked Nov 20 '25 09:11

Lopfest


1 Answers

The regex engine in Java does not support subroutines (as in PHP or Ruby).

Thus, you may work around it by defining the repeated subpatterns as separate variables and use them to build the final regex:

String block = "somelongpattern[0-9]";
String final_regex = "^(" + block + ")([,; ]+" + block + ")*$";

Or using String.format:

String block = "somelongpattern[0-9]";
String final_regex = String.format("^(%1$s)([,; ]+%1$s)*$",block);

See the online demo.

like image 53
Wiktor Stribiżew Avatar answered Nov 23 '25 00:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!