1

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

1
  • Yes. But is it only two characters? Commented Apr 20, 2016 at 14:31

3 Answers 3

2

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.

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

Comments

1

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

Comments

0

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] 

2 Comments

I'm pretty sure OP was giving an example with this little 2 char thing
Well he can use the lookahead solution in any context : check with lookahead, match what you want, alternate to specify an "else" block. However I don't think you should be thinking this way in regex, it won't help you much

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.