108

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

2
  • Looks ok, what problem are you having? Commented Jan 9, 2010 at 0:45
  • 1
    yeah, should work. cletus, danben, and myself agree. also, @danben - my name is Dan Beam, lol, so close! Commented Jan 9, 2010 at 0:49

1 Answer 1

179

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"));
Sign up to request clarification or add additional context in comments.

2 Comments

What if i need to delimit these strings from other pieces of the regex that are also strings? e.g. eee(ff|gg)eee Do I have to use parentheses?
Ah nevermind. Your update fixes it. The last example is what I was looking for. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.