Is it possible to build a template based on two helper patterns in Java

Pattern p1 = Pattern.compile("................."); Pattern p2 = Pattern.compile("xxxxxxxxxxxxxxxxxxx"); 

Since p1 and p2 are quite long, it is difficult to write a single template covering all cases in p1 and p2. Is it possible to write another p3 template that is built on p1 and p2, so that I can only run one Matcher:

 Matcher m = p3.matcher(str); 
+6
source share
2 answers

You can use this to combine patterns:

 Pattern pattern = Pattern.compile(".................|xxxxxxxxxxxxxxxxxxx"); 

to match one:

 Matcher matcher = pattern.matcher(s); 
+3
source

Of course, you can simply combine pattern strings with | . If you have strings representing patterns string1 and string2 , then string1|string2 will match any pattern. In your example, you can use the string ".................|xxxxxxxxxxxxxxxxx" .

Of course, things get more complicated if you use capture groups or repeatedly match patterns with substrings, because then it is not clear what it means to β€œcombine” patterns, but for simple matching / no -math, this works.

+1
source

Source: https://habr.com/ru/post/1012081/


All Articles