[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How to use regex to search string between {}?

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}'>