I have a javascript regex that matches an incrementing numerical value using look ahead however, I feel this can be simplified.
I currently am using /^(?=[1-5]{5}$)(?=(?=.*([1]))(?=.*([2]))(?=.*([3]))(?=.*([4]))|(?=.*([2]))(?=.*([3]))(?=.*([4]))(?=.*([5])))d+$/gm
to identify if at least 4 digits in a 5 digit string have values that increment by 1.
Rules:
- Can only contain numbers 1-5 and there must only be 5 characters in the string =
(?=[1-5]{5}$)
- 4 of the 5 numbers must increment by 1, they do not have to be grouped together.
- Here I have entered 4 literal groups for each potential incrementing 4 digit string
(?=.*([1]))(?=.*([2]))(?=.*([3]))(?=.*([4]))
and(?=.*([2]))(?=.*([3]))(?=.*([4]))(?=.*([5]))
. These are inside a look ahead with anor
separator.
Here is an example of strings that match the regex:
12343
– 4 numbers increment in order starting at the 1
32142
– 4 numbers increment, but not in order starting with the 1
23451
– 4 numbers increment in order starting at the 2
52345
– 4 numbers increment in order starting at the 2
34152
– 4 numbers increment out of order, here we have 2 matches that are not in order, only one match is required
12345
– 4 numbers increment in order, here we have 2 matches that are both in order, only one match is required
My regex seems to work with my tests, however I just feel there is a more dynamic and cleaner approach to this that I am just not privy to as my regex skills are below par to say the least.