java Java中的条件正则表达式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3687921/
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
Conditional Regular Expression in Java?
提问by RNeuendorff
I have a conditional regular expression that works on regex test websites, such as regexlib.com, but cannot get it to work in my Java application.
我有一个在 regex 测试网站(例如 regexlib.com)上工作的条件正则表达式,但不能让它在我的 Java 应用程序中工作。
But, http://www.regular-expressions.info/conditional.htmlindicates that Java doesn't support conditionals, but I've seen other posts on SO imply that it does.
但是,http://www.regular-expressions.info/conditional.html表明 Java 不支持条件,但我已经看到其他关于 SO 的帖子暗示它支持。
An example of my RegEx is: (?(?=^[0-9])(317866?)|[a-zA-Z0-9]{6}(317866?))
我的正则表达式的一个例子是: (?(?=^[0-9])(317866?)|[a-zA-Z0-9]{6}(317866?))
It should match either of these inputs: 317866
or 317866A12
or FCF1CS317866
它应该符合以下任一输入:317866
或317866A12
或FCF1CS317866
How do I work around this Java limitation?
如何解决此 Java 限制?
TIA
TIA
回答by Eugene Kuleshov
Conditional expressions are not supported by java.util.regex.Patternclass. To get around that you could use a 3rd party regexp library such as JRegex
java.util.regex.Pattern类不支持条件表达式。为了解决这个问题,您可以使用 3rd方正则表达式库,例如JRegex
回答by Mark Byers
How about just doing this instead?
只是这样做怎么样?
(?:[a-zA-Z0-9]{6})?(317866?)
Or if you know that the longer version always start with a letter then you can use this:
或者,如果您知道较长的版本总是以字母开头,那么您可以使用以下命令:
(?:[a-zA-Z][a-zA-Z0-9]{5})?(317866?)
It will first try to match 6 alphanumerics followed by 31786 or 317866, and if that fails it will then backtrack and try matching 31786 or 317866.
它将首先尝试匹配 6 个字母数字,然后是 31786 或 317866,如果失败,它将回溯并尝试匹配 31786 或 317866。