2

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.

2 Answers 2

4
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.

Sign up to request clarification or add additional context in comments.

2 Comments

Champion. I needed it to include the "PakBusPort_" portion but changing it to p = re.compile(r'{(PakBusPort_.*?)}') Gave me the result I was after.
Welcome to Stack Overflow, and don't forget to mark good solutions as Accepted Answer. It helps visitors and rewards the answerer.
0

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')]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.