How to Match ONLY on specific items in String and No More

Viewed 46

Given the sample String of 7,8,9 the three values of a Seven, an Eight and a single Nine are the ONLY valid values. These values could also be out of order for example 8,7,9. However if ANY other value is within that string the MATCH needs to fail. I'm currently unsure how to expand my existing Pattern to now FAIL the match should there be any other entries outside of the 7, 8 or 9 found in the string.

More String examples:

7,8,9,8,7 This is valid (Contains ONLY valid numbers of 7,8 and 9)

8,9,77 Not Valid (has other values other than 7,8,9)

8 Valid (Contains one single valid value)

8,17 Not Valid (has other values other than 7,8,9)

9,thisistextbetweencomma,7,9,19 Not Valid (has other values other than 7,8,9)

After some work the below is a Regular Expression that works to Match on Strings that have any single digit 7s, 8s and/or 9s found within it. This Pattern is used to detect IF a string contains any values of 7s 8s or 9s.

Demo Showing how to detect if the String has a 7, 8 or 9 and the PATTERN is below:

/(?<=^|,)[789](?=,|$)/gm

I am needing to expand on the above to Fail the match should there be OTHER values found within the string that are NOT single 7s, 8s or 9s and I am not currently able to do this.

Again my PATTERN which I've provided above still Matches on the 7s, 8s or 9s even if the string has invalid entries.

The below screenshot is for Context ONLY and is not needed to answer this question. It simply shows that I am applying these RegEx Patterns into a SQL Server RegexMatches Custom Table Valued Function. It is designed to return back the Matched Text if matched on as well as up to 9 capturing groups. I will later be applying Min/Max and other aggregate functions against the matched results table AFTER I've learned the correct Regex Pattern to obtain these matches and groups.

SQL Server RegexMatches TVF

1 Answers

You can use

(?:\G(?!^),|^(?=[7-9](?:,[7-9])*$))([7-9])

See the regex demo.

Details:

  • (?:\G(?!^),|^(?=[7-9](?:,[7-9])*$)) - either of the two alternatives:
    • \G(?!^), - end of the previous successful match (start of string position that \G can also match is excluded with the help of the (?!^) negative lookahead) and then a comma
    • | - or
    • ^(?=[7-9](?:,[7-9])*$) - a start of a string (or line if you use a multiline flag) that is immediately followed with a digit from 7 to 9 and then zero or more occurrences of a , and a digit from 7 to 9 till end of the string/line
  • ([7-9]) - Group 1: a 7, 8 or 9 char.
Related