Regex reuse a pattern to capture multiple groups?

前端 未结 2 1500
南方客
南方客 2020-11-29 14:00

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

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

This will match for e

2条回答
  •  醉话见心
    2020-11-29 14:43

    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.

提交回复
热议问题