tags:

views:

235

answers:

1

Hey guys I wanted to ask if you can do some conditional checks on a single regular expression using lookahead or any other mechanism.

For example in my regex I want to the next value to range from 0-5 if the previous was over 3 or range from 0-9 if the previous was under 3.

Eg:

[0-9] next match should be either [0-5] OR [0-9] depending on whether the previous value was under or over 5.

as code think of it like this:

calls this A--> [0-9][0-9]<-- call this B

if (A < 5) then B [0-9] Else B [0-5]

Is this possible as a single regular expression?

+3  A: 

This is the format for a positive lookahead:

/(?=expression)/

And this is the negative lookahead:

/(?!expression)/

EDIT

For your example, this would mean something like this:

/((?=[5-9]+)[0-5]+)|((?=[0-4]+)[0-9]+)/
Franz
This is assuming "over 3" includes 3.
Franz
ahha that could be it i'm guessing "|" is the OR operator?
iQ
Yes, a pipe (`|`) is an OR in regex.
Amber
Adapted your edits, btw.
Franz
thank that was exactly what I was looking for, didn't know regex has that perfect!
iQ
Oh, one more assumption I made is that you want to allow at least one, but also possibly multiple digits of each type (hope you understand). If not, if every "character" class is only supposed to appear once, just remove the plus sign in all four occasions.
Franz