Conditional regex in Java?

I have a conditional regex that works on regex test websites like regexlib.com but cannot make it work in my Java application.

But http://www.regular-expressions.info/conditional.html indicates that Java does not support conventions, but I saw that other posts on SO imply that they

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

It must match any of these inputs: 317866 or 317866A12 or FCF1CS317866

How do I get around this Java restriction?

TIA

+4
source share
2 answers

Conditional expressions are not supported by the java.util.regex.Pattern class. To get around this, you can use a third-party regex library like JRegex

+5
source

How to do it instead?

  (?: [a-zA-Z0-9] {6})? (317866?)

Or, if you know that a longer version always starts with a letter, you can use this:

  (?: [a-zA-Z] [a-zA-Z0-9] {5})? (317866?)

First, it will try to match 6 alphanumeric characters, followed by 31786 or 317866, and if that fails, it will back off and try to match 31786 or 317866.

+1
source

All Articles