tags:

views:

256

answers:

3

I need a regex pattern to match a sequence of 3 consecutive digits in a string that are consecutively increasing or decreasing.

For example:

These strings should match (xxx123xxx, 789xxxxxx, xxxxxx987, xxxxxx432)

These strings should not match (xxxxxx454, 333xxxxxx, xxx429xxx)

+8  A: 

There is no other way than listing them:

(012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210)
Gumbo
This is technically the correct answer, but I agree that Regex is not necessarily the best way to accomplish the task. Regex should be used to find the 3 digit pattern and then further testing should be used to find if that 3 digit pattern is consecutively increasing/decreasing.
@matt.kovacs: That’s a great conclusion.
Gumbo
+2  A: 

This is going to be a very complicated regex. On a project where I had to do something very similar, I ended up matching digit groups and then passing off the actual validation of the digits to a delegate (I was doing this in C++ code; have done something similar on another project in Java in the same way).

If at all possible, this is what I'd recommend doing here. A regex which could do this all by itself would be very difficult to read or maintain.

M1EK
+2  A: 

This can be done simply, but only with defining the valid sets of consecutive digits

(?:012|210|123|321|234|432|345|543|456|654|567|765|678|876|789|987)

rrrr