Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regular expression OR operator

Tags:

java

regex

This may be a dumb question, but I couldn't find it anywhere:

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

e.g: Tel|Phone|Fax

like image 431
Eric Conner Avatar asked Jan 09 '10 00:01

Eric Conner


Video Answer


1 Answers

You can just use the pipe on its own:

"string1|string2" 

for example:

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

Output:

blah, blah, string3 

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

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

has the same output. but if you just do this:

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

you get:

blah, stringblah, string3 

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3"; System.out.println(s.replaceAll("string(?:1|2)", "blah")); 
like image 115
cletus Avatar answered Sep 23 '22 05:09

cletus