简体   繁体   中英

Find all occurrences of a regex pattern and replace with eval output

I have a txt file which contains a lot of strings such as

Chr(101)
Chr(97)
Chr(104)
...

I am using the below code to find all occurrences of such strings using regex. What I'd like to do is to replace each occurrence with its evaluated output. So in this case I'd replace the above with:

e
a
h

The code I have is as follows:

with open(oFile, "r") as f:
    for line in f:
      # find all occurrences of Chr(\d+\) and put in a list
      chrList = [str(s) for s in re.findall(r'Chr\(\d+\)', line)]
      # print chrList 
      for c in chrList:
        # print eval(c.lower())
        out = re.sub(c, eval(c.lower()), line)

If I print the eval(c.lower()) line then it outputs as expected. However the re.sub line fails with the following error:

 raise error, v # invalid expression sre_constants.error: bogus escape (end of line) 

Not sure where I'm going wrong here.

You don't have to use distinct search and replace functions. You can invoke eval using the functional form of re.sub :

for line in f:
  out = re.sub(r'Chr\(\d+\)', lambda c: eval(c.group(0).lower()), line)
  print out

Your going to want to escape your search pattern because parenthesis are special characters in regular expressions . You can easily do this using re.escape .

out = re.sub(re.escape(c), eval(c.lower()), line)

And as an example:

strings = ['Chr(100)', 'Chr(101)', 'Chr(102)']
values = [re.sub(re.escape(c), eval(c.lower()), c) for c in strings]

# ['d', 'e', 'f']

That being said, why not just use replace() ?

out = line.replace(c, eval(c.lower())

Same thing but without eval() or imports:

strings = ['Chr(100)', 'Chr(101)', 'Chr(102)']
values = [chr(x) for x in (int(c.replace("Chr(", "").replace(")","")) for c in strings)]

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