Reputation: 379
I am not familiar with Regex. Actually, I've just started with it. I have three different patterns
pattern = re.compile(r'SETUP...\d+')
pattern = re.compile(r'PRO...\d+')
pattern = re.compile(r'INSTALL...\d+')
Some of my strings are SETUP1234, SETUP = 1234, SETUP 1234, SETUP-1234
etc. The same with the others. So, I decide that 3 characters between the prefix and the numbers is a reasonable way to use it. But my problem now is, can I combine the three of them in one Regex instead of calling three different findall
?
Upvotes: 2
Views: 45
Reputation: 239693
You can use |
like this
pattern = re.compile(r'(SETUP|PRO|INSTALL)...\d+')
it means that any of SETUP
, PRO
or INSTALL
.
Also, the pattern can be improved a little, like this
pattern = re.compile(r'(SETUP|PRO|INSTALL).{1,3}\d+')
This allows 1 to 3 characters to be used in between the words and the numbers.
As Tim suggested in the comments, you can use non-capturing group like this
pattern = re.compile(r'(?:SETUP|PRO|INSTALL).{1,3}\d+')
print pattern.findall("SETUP 1234")
# ['SETUP 1234']
print pattern.findall("PRO 1234")
# ['PRO 1234']
print pattern.findall("INSTALL 1234")
# ['INSTALL 1234']
Upvotes: 4