Home > OS >  How can I modify 2 regex that currently match 3 numbers to match the same 3 numbers at the end of a
How can I modify 2 regex that currently match 3 numbers to match the same 3 numbers at the end of a

Time:10-13

I have a regular expression that I use to find the number 556 and 567 in any order. Now I am looking to modify the regex so that search will match the same 3 numbers in the last 3 digits of a 4 digit number.

First Regex that matches 556 in any order:

"\b(?=[0-46-9]*5[0-46-9]*5[0-46-9]*\b)(?=\d{3})\d*6\d*\b"

I would like the new regex to match the below([0-9]556,[0-9]565,[0-9]655). desired results:

0556
0565
0655
1556
1565
1655........

Second Regex that matches 567 in any order:

"\b(?=[0-46-9]*5)(?=[0-57-9]*6)(?=[0-689]*7)\d \b"

Desired Results:

7756
7765
8567
8576
8657
8675
8756
8765.....

CodePudding user response:

You could match the first digit, then assert a length of 3 digits till the end of the string.

Assert at least a single 6, and then match 2 times a 5 between optional 6'es.

Use a character class to restrict the possible matches for the digits

^\d(?=[56]{3}$)(?=[56]*6)6*56*56*$

Regex demo

This is shorter written as ^\d(?:556|565|655)$

For the second pattern you can use a same approach, match a single digit, assert a 5 and a 6 followed by matching a 7.

^\d(?=[567]{3}$)(?=[567]*5)(?=[567]*6)[567]*7[567]*$

Regex demo

This is shorter written as ^\d(?:567|576|657|675|756|765)$

  • Related