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

1
  • Should it match 31786? If not, what is that ? doing after the last 6? Commented Sep 10, 2010 at 20:42

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

6 Comments

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: 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: That regex is not completely accurate. I do not want to match something like "AB1363183A23", but that regex does.
@RNeuendorff: Are you sure about that? The string you gave as an example doesn't even contain 31786 so how could it match?
@RNeuendorff: The best test is to write a short Java program to test them. It takes only about 3 or 4 lines of code.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.