user1050619
user1050619

Reputation: 20886

Regular expression - Set of possible character matches

I need to test a regular expression for a set of possible character matches,

The field 'TEST' can take these possible values - 'TEST1','TEST2','TEST3'...'TEST10'

import re
pattern = 'TEST[0123456789]
field = 'TEST1'

match = re.search(match,field)

How do I specify the value of [10] in the pattern matching?

Upvotes: 1

Views: 80

Answers (2)

Tom Lord
Tom Lord

Reputation: 28305

TEST(?:[1-9]|10)\b

This fixes a couple of scenarios that the other answers here did not.

In action: http://www.rubular.com/r/0if2CHfa6l

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1123420

10 is a 2-character string:

r'TEST\d{1,2}'

would match one or two digits; \d matches any character in the range from 0 through to 9; it is the shorthand equivalent of [0123456789].

Alternatively, use two alternatives:

r'TEST(?:\d|10)'

would allow for 1 digit, or would allow for 10. Note that it'll still match TEST11 because that string starts with TEST1. Add a boundary test if you want to prevent that to match still:

r'TEST(?:\d|10)\b'

Demo of that last pattern:

>>> re.search(r'TEST(?:\d|10)\b', 'TEST0').group()
'TEST0'
>>> re.search(r'TEST(?:\d|10)\b', 'TEST8').group()
'TEST8'
>>> re.search(r'TEST(?:\d|10)\b', 'TEST10').group()
'TEST10'
>>> re.search(r'TEST(?:\d|10)\b', 'TEST11') is None
True

Upvotes: 7

Related Questions