Java 正则表达式 OR 运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2031805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 02:49:06  来源:igfitidea点击:

Java regular expression OR operator

javaregex

提问by Eric Conner

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?

如何使用没有括号的 java OR 正则表达式运算符 (|)?

e.g: Tel|Phone|Fax

例如:电话|电话|传真

采纳答案by cletus

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".

因为你说的是​​“string1”或“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"));