Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional Regular Expression in Java?

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.

But, http://www.regular-expressions.info/conditional.html indicates that Java doesn't support conditionals, but I've seen other posts on SO imply that it does.

An example of my RegEx is: (?(?=^[0-9])(317866?)|[a-zA-Z0-9]{6}(317866?))

It should match either of these inputs: 317866 or 317866A12 or FCF1CS317866

How do I work around this Java limitation?

TIA

like image 612
RNeuendorff Avatar asked Sep 10 '10 20:09

RNeuendorff


2 Answers

Conditional expressions are not supported by java.util.regex.Pattern class. To get around that you could use a 3rd party regexp library such as JRegex

like image 112
Eugene Kuleshov Avatar answered Sep 24 '22 23:09

Eugene Kuleshov


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.

like image 32
Mark Byers Avatar answered Sep 22 '22 23:09

Mark Byers