Fighting Conditional Regular Expressions

I have a simple problem, but I can not solve it. Or, my string is in the format ID: dddd with the following regular expression:

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

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

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

Now I want to make one regex that can handle both. The first thing I came up with was the following:

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

It matches, but I looked at conditional regular expressions and thought that something should be possible line by line (pseudo-codish)

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

I canโ€™t get it right. I thought I should use /?=/ , But I have no idea. Sort of

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

but it does not work.

You can help?

+4
source share
3 answers

Are you looking for ^ID: (\d+)(?: Status: (\d+))?$

edit : Since the question is marked as Ruby, it is worth mentioning that according to this question and this taste comparison , Ruby does not execute conditional regex.

http://www.regular-expressions.info is an excellent source on this subject.

+6
source

You need .* In your view: (Rubular)

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

However, for your specific example, you do not need an appearance. Can you use a quantifier instead ? : (Rubular)

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

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

Have you (or any of the respondents) read otherwise? If so, it might be useful to update the related question so that it no longer provides incorrect information.

+2
source

All Articles