How to use regex to search string between {}?

Chris Angelico rosuav at gmail.com
Fri Aug 23 04:47:30 EDT 2019


On Fri, Aug 23, 2019 at 6:44 PM lampahome <pahome.chen at mirlab.org> wrote:
>
> I want to parse a path string with multiple files and try to figure out a
> one-line way.
>
> If I have path: /home/admin/hello/yo/{h1,h2,h3,h4}
>
> What I thought is use regex.search, but the pattern always failed.
>
> I use below:
> import re
> path = /home/admin/hello/yo/{h1,h2,h3,h4}
> r = re.search('{.}', path)
> # r should be ['h1,h2,h3,h4'] but I fail
>
> Why always search nothing?

Because a dot matches *one single character*. If you want to match
multiple characters, you have to say so:

>>> re.search("{.*}", "/home/admin/hello/yo/{h1,h2,h3,h4}")
<re.Match object; span=(21, 34), match='{h1,h2,h3,h4}'>

ChrisA



More information about the Python-list mailing list