Java OR regex operator

This might be a stupid question, but I couldn't find anything:

How can I use the java regex operator OR (|) without parentheses?

for example: Phone | Phone | Fax

+68
java regex
Jan 09 2018-10-09T00:
source share
1 answer

You can simply use the pipe yourself:

"string1|string2" 

eg:

 String s = "string1, string2, string3"; System.out.println(s.replaceAll("string1|string2", "blah")); 

Output:

 blah, blah, string3 

The main reason for using parentheses is to limit the scope of alternatives:

 String s = "string1, string2, string3"; System.out.println(s.replaceAll("string(1|2)", "blah")); 

has the same result. but if you just do it:

 String s = "string1, string2, string3"; System.out.println(s.replaceAll("string1|2", "blah")); 

You get:

 blah, stringblah, string3 

because you said "string1" or "2".

If you do not want to use this part of the expression, use ?: ::

 String s = "string1, string2, string3"; System.out.println(s.replaceAll("string(?:1|2)", "blah")); 
+115
Jan 09 2018-10-09T00:
source share



All Articles