mel mel - 1 year ago 74
Python Question

Finding a pattern in python using re (reggae)

I'm trying to build a regular expression:

mystring = /some/path/with/%variable%/%inside%/%it%/
re.findall("[^\s%]+", allocine_spec[key])

And this return the following:

['/some/path/', 'variable', '/', 'inside', '/', 'it']

But I would like only:

['variable', 'inside', 'it']

Is that possible using only re?

Answer Source

You need a much simpler regex:


See the regex demo

This will match a %, then capture 1+ chars other than % into Group 1 and then will match a trailing %. If your strings only contain word characters in between %, you may replace [^%]+ with \w+.

Note that re.findall returns only the captured substrings if capturing groups are defined in the pattern.

Python demo:

import re
mystring = "/some/path/with/%variable%/%inside%/%it%/"
print(re.findall("%([^%]+)%", mystring))
# => ['variable', 'inside', 'it']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download