9

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

RNeuendorff
  • 91
  • 1
  • 1
  • 3

2 Answers2

11

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

Eugene Kuleshov
  • 31,461
  • 5
  • 66
  • 67
1

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Thanks for the quick replies... I'm not real familiar with RegEx and I didn't realize it could be that simple. My business rules are: if it starts with an alpha, ignore the first 6, if it starts with a numeric, start the match from the beginning. So, the second example seems to be more complete. – RNeuendorff Sep 10 '10 at 20:16
  • @RNeuendorff: The second example should work and it will not match `123456316866`, which the first expression will match. I think you want the second example. – Mark Byers Sep 10 '10 at 20:20
  • @Mark Byers: That regex is not completely accurate. I do not want to match something like "AB1363183A23", but that regex does. – RNeuendorff Sep 10 '10 at 20:28
  • @RNeuendorff: Are you sure about that? The string you gave as an example doesn't even contain `31786` so how could it match? – Mark Byers Sep 10 '10 at 20:42
  • Sorry, I'm working with a couple examples and pasted the wrong string... Now I'm getting odd results from the Regex Test sites... – RNeuendorff Sep 10 '10 at 21:01
  • 1
    @RNeuendorff: The best test is to write a short Java program to test them. It takes only about 3 or 4 lines of code. – Mark Byers Sep 10 '10 at 21:21