nathanvda
nathanvda

Reputation: 50057

struggling with conditional regular expressions

I have a simple problem, yet i am unable to solve this. Either my string has a format ID: dddd, with the following regular expression:

/^ID: ([a-z0-9]*)$/

or as follows: ID: 1234 Status: 232, so with the following regular expression:

/^ID: ([a-z0-9]*) Status: ([a-z0-9]*)$/

Now i want to make one regular expression that can handle both. The first thing i came up with was this:

/^ID: ([a-z0-9]*)$|^ID: ([a-z0-9]*) Status: ([a-z0-9]*)$/

It matches, but i was looking into conditional regular expressions, and was thinking that something should be possible along the lines of (pseudo-codish)

if the string contains /Status:/
    /^ID: ([a-z0-9]*)$/
else
    /^ID: ([a-z0-9]*) Status: ([a-z0-9]*)$/

only, i can't get this expressed correctly. I thought i should be using /?=/ but have no clue how. Something like

/((?=Status)^ID: ([a-z0-9]*) Status: ([a-z0-9]*)$|^ID: ([a-z0-9]*)$/

but that doesn't work.

Can you help?

Upvotes: 5

Views: 2628

Answers (3)

Chris Wesseling
Chris Wesseling

Reputation: 6368

You're looking for ^ID: (\d+)(?: Status: (\d+))?$

edit: Since the question is tagged Ruby it's worth mentioning that according to both this question and this flavour-comparison, Ruby doesn't do conditional regex.

http://www.regular-expressions.info is a great source on the subject.

Upvotes: 7

jerhinesmith
jerhinesmith

Reputation: 15492

Interestingly, according to this question, Ruby 1.8/1.9 does not support conditional regular expressions.

Have you (or any of the answerers) read otherwise? If so, it might be helpful to update the linked question so that it no longer gives incorrect information.

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838276

You need a .* in your lookahead: (Rubular)

/(?=.*Status)^ID: ([a-z0-9]*) Status: ([a-z0-9]*)$|^ID: ([a-z0-9]*)$/

However, for your specific example you don't need a lookahead. You can just use the ? quantifier instead: (Rubular)

/^ID: ([a-z0-9]*)(?: Status: ([a-z0-9]*))?$/

Upvotes: 3

Related Questions