tags:

views:

57

answers:

3

I have a regex that works: ABC-[0-9]+

I also have a regex: DEF-[0-9]+

But I don't get how to combine the two so it will match them both

I tried ABC-[0-9]+ | DEF-[0-9]+ but it didn't really work...

This is all in Java regex if it matters.

Any help's appreciated!

+7  A: 

If you want a regular expression that matches sequences that start with either ABC or DEF, try this:

(ABC|DEF)-[0-9]+

But except from the two space characters around |, your regular expression should match that too:

ABC-[0-9]+|DEF-[0-9]+

These two regular expressions match the same set of strings.

Gumbo
Won't that cause it to pull out only the ABC and DEF, being a Java regex?
glowcoder
@glowcoder: `(ABC|DEF)-[0-9]+` has capturing group 1, which will capture either `ABC` or `DEF`. Group 0 still exists (as always) and will match the entire string with the dash and digits. See http://www.regular-expressions.info/brackets.html or http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#cg . That said, it's true that some regex frameworks will perform various special treatments when the pattern has _EXACTLY ONE_ capturing group, but as far as I know Java isn't one of them.
polygenelubricants
@polyg Thanks for the helpful explanation.
glowcoder
A: 

You need to group the two regexes, use an atomic group:

(?>ABC-[0-9]+)|(?>DEF-[0-9]+)

Bob Fincheimer
A: 

Try (ABC-[0-9]+)|(DEF-[0-9]+)

Charlie Martin