How to match strings that are entirely composed of a predefined set of substrings. For example, I want to see if a string is composed of only the following allowed substrings:
- ,
- 034
- 140
- 201
In the case when my string is as follows:
034,201
The string is fully composed of the 'allowed' substrings, so I want to positively match it. However, in the following string:
034,055,201
There is an additional 055, which is not in my 'allowed' substrings set. So I want to not match that string.
What regex would be capable of doing this?
CodePudding user response:
Try this one:
^(034|201|140|,) $
Step by step:
^begining of a line(034|201|140|,)captures group with alternative possible matchescaptured group appears one or more times$end of a line
CodePudding user response:
This regex will match only your values and ensure that the line doesn't start or end with a comma. Only matches in group 0 if it is valid, the groups are non-matching.
^(?:034|140|201)(?:,(?:034|140|201))*$
^: start(?:034|140|201): non-matching group for your set of items (no comma)(?:,(?:034|140|201))*: non-matching group of a comma followed by non-matching group of values, 0 or more times$: end
