Reputation: 3037
I'm new to python and am trying to figure out python regex to find any strings that match -. For example, 'type1-001'
and 'type2-001'
should be a match, but 'type3-asdf001'
shouldn't be a match. I would like to be able to match with a regex like [type1|type2|type3]-\d+
to find any strings that start with type1
, type2
, or type3
and then are appended with '-'
and digits. Also, it would be cool to know how to search for any upper case text appended with '-' and digits.
Here's what I think should work, but I can't seem to get it right...
pref_num = re.compile(r'[type1|type2]-\d+')
Upvotes: 0
Views: 11268
Reputation: 54
[]
will match any of the set of characters appearing between the brackets. To group regexes you need to use ()
. So, I think your regex should be something like:
pref_num = re.compile(r'(type1|type2)-\d+')
As to how to search any uppercase text appended with -
and digits, I would suggest:
[A-Z]+-\d+
Upvotes: 3
Reputation: 16266
pref_num = re.compile(r'(type1|type2|type3)-\d+')
m = pref_num.search('type1-000')
if m != None: print(m.string)
m = pref_num.search('type2-000')
if m != None: print(m.string)
m = pref_num.search('type3-abc000')
if m != None: print(m.string)
Upvotes: 0
Reputation: 3535
If you only want the digit after "type" to be variable then you should put only those in the square brackets like so:
re.compile(r'type[1|2]-\d+')
Upvotes: 2
Reputation: 118011
You can use the pattern
'type[1-3]-[0-9]{3}'
Demo
>>> import re
>>> p = 'type[1-3]-[0-9]{3}'
>>> s = 'type2-005 with some text type1-101 and then type1-asdf001'
>>> re.findall(p, s)
['type2-005', 'type1-101']
Upvotes: 0