Question

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?

Was it helpful?

Solution

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]+)/
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top