Reputation: 63
I am trying to extract a portion from a string in python 2.7 using a regular expression (re module).
The best I can get is
res = "{{PakBusPort_somename} 11942 pakbus-port 1}\r\n{{Somename} 5436 CR800-series 2}"
p = re.compile('PakBusPort_')
m = p.findall( res )
Which will give me "PakBusPort_". But I also need it to give me the "somename" portion.
Basically I need everything in between { and } that starts with "PakBusPort_". I have tried
p = re.compile('PakBusPort_.*}}')
But no results.
I am a bit of a noob with regular expressions so any help would be appreciated.
Upvotes: 2
Views: 184
Reputation: 11534
You were close, this should give you back a list of tuples matching your regex:
res = '{{PakBusPort_somename} 11942 pakbus-port 1}\r\n{{Somename} 5436 CR800-series 2}'
p = re.compile('{(PakBusPort)_([^}]*)}')
m = p.findall( res )
print m
[('PakBusPort', 'somename')]
Upvotes: 0
Reputation: 500357
In [71]: p = re.compile(r'{PakBusPort_(.*?)}')
In [72]: p.findall(res)
Out[72]: ['somename']
If you also need to include PakBusPort_
, move the opening parenthesis:
In [73]: p = re.compile(r'{(PakBusPort_.*?)}')
In [74]: p.findall(res)
Out[74]: ['PakBusPort_somename']
The question mark is needed to make the match non-greedy, meaning that it'll stop at the first }
rather than matching everything till the last one.
Upvotes: 4