Mike
Mike

Reputation: 265

Regex with if statement

Is there a way to include an if statement in a regular expression, in javascript. This sort of thing:

var regex = /"if followed by [0-9] then match [a-m], else match [n-z]"/i

so:

"a9" //returns a match
"aa" //doesn't return a match
"na" //returns a match

I hope this makes sense.

Thanks in advance

Upvotes: 1

Views: 2986

Answers (3)

Alfeu
Alfeu

Reputation: 991

Not exactly an if, but an alternation and look-ahead are what you need in this case:

([a-m](?=[0-9])|[n-z](?![0-9]))

Here is a working example.

Upvotes: 2

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You would need this:

([a-m][0-9])|([n-z][a-m])

Or, if that is full of alphabets, then:

([a-m][0-9])|([n-z][a-z])

For the given input, it gives:

MATCH 1
1.  `a9`
MATCH 2
2.  `na`

Check online at RegEx 101.

Working

Explanation

Upvotes: 1

Aaron
Aaron

Reputation: 24812

The closest equivalent to if in regex is the alternation, |, where the regex will match as far as it can in a branch of the alternation, and try to match the next one(s) if it fails.

To code your exact statement in regex, one would use (?=.[0-9])[a-m]|[n-z] where you use lookahead to check the condition.

However you can use this much simpler regex :

[a-m][0-9]|[n-z]

Upvotes: 0

Related Questions