这可能是个愚蠢的问题,但我在任何地方都找不到它:
如何使用没有括号的 javaOR 正则表达式操作符(|) ?
例如: 电话 | 电话 | 传真
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"));