java 我们可以在java中使用正则表达式检查多个模式吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2457185/
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
can we check multiple patterns using regex in java?
提问by Praveen
i want to check 2 patterns using regex.
我想使用正则表达式检查 2 个模式。
can i check those both patterns in the same time (like if(condition1 | condition2) condition).
我可以同时检查这两种模式吗(如 if(condition1 | condition2) 条件)。
any idea?
任何的想法?
回答by Daniel Silveira
You can do it exactly the way you did, with pipe separating the two+ expressions
你可以完全按照你的方式来做,用管道分隔两个+表达式
For instance: The regular expresion (abc)|(def)would match abcOR def
例如:正则表达式(abc)|(def)将匹配abcORdef
回答by Praveen
It really depends - namely, you can design your regex with "or" modifiers like this "(match this)|(or this)". If you use carefully designed regex, you only need to do this:
这真的取决于——也就是说,你可以用“或”这样的修饰符来设计你的正则表达式"(match this)|(or this)"。如果你使用精心设计的正则表达式,你只需要这样做:
Pattern p1 = Pattern.compile(regex)
Matcher m = p1.matcher(searchstring)
Once. This is probably the most efficient way to go about things. The other option is to run two matcher/pattern object pairs, run findoperations until findreturns false than count the number of outputs. If they're both > 0 you're in business. The other option is if you only need one or more matches, to do:
一次。这可能是最有效的处理方式。另一种选择是运行两个匹配器/模式对象对,运行find操作直到find返回假而不是计算输出的数量。如果它们都 > 0,你就在做生意。另一种选择是,如果您只需要一个或多个匹配项,请执行以下操作:
if ( matcher1.find() & matcher2.find() )
{
...
}

