简体   繁体   中英

replace regex variable with string in python

I have a situation where I have a regular expression like this

regex_string = r'(?P<x>\d+)\s(?P<y>\w+)'
r = re.compile(regex_string)

and, before I start matching things with it, I'd like to replace the regex group named x with a particular value, say 2014. This way, when I search for matches to this regular expression, we will only find things that have x=2014 . What is the best way to approach this issue?

The challenge here is that both the original regular expression regex_string and the arbitrary replacement value x=2014 are specified by an end user. In my head, the ideal thing would be to have a function like replace_regex :

r = re.compile(regex_string)
r = replace_regex_variables(r, x=2014)
for match in r.finditer(really_big_string):
    do_something_with_each_match(match)

I'm open to any solution, but specifically interested in understanding if its possible to do this without checking matches after they are returned by finditer to take advantage of re 's performance. In other words, preferrably NOT this :

r = re.compile(regex_string)
for match in r.finditer(really_big_string):
    if r.groupdict()['x'] == 2014:
        do_sometehing_with_each_match(match)

You want something like this, don't you?

r = r'(?P<x>%(x)s)\s(?P<y>\w+)'
r = re.compile(r % {x: 2014})
for match in r.finditer(really_big_string):
    do_something_with_each_match(match)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM