Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using python finditer, how can I replace each matched string?

I am using Python (pl/python, actually) to find, successively, a series of regex matches in a very large text object. This is working fine! Each match is a different result, and each replace will be a different result, eventually based on a query inside the loop.

For the moment, I'd be happy to replace every match in rx with any text, just so I'd understand how it works. Can someone give me an explicit example of replacing the matched text?

match.group(1) seems to correctly indicate the matched text; is this the way to do things?

plan3 = plpy.prepare("SELECT field1,field2 FROM sometable WHERE indexfield = $1", 
  [ "text" ])

rx = re.finditer('LEFT[A-Z,a-z,:]+RIGHT)', data)

# above does find my n matches...

# -------------------  THE LOOP  ----------------------------------
for match in rx:
 # below does find the 6 match objects - good!

 # match.group does return the text
 plpy.notice("--  MATCH: ", match.group(1))

 # must pull out a substring as the 'key' to an SQL find (a separate problem)
 # (not sure how to split based on the colon:)
 keyfield = (match.group(1).split, ':')
 plpy.notice("---------: ",kefield)

try:
 rv = plpy.execute(plan3, [ keyfield ], 1 )

# ---  REPLACE match.group(1) with results of query
# at this point, would be happy to replace with ANY STRING to test...
except:
 plpy.error(traceback.format_exc())

# -------------------  ( END LOOP )  ------------------------------
like image 831
DrLou Avatar asked Jun 20 '11 01:06

DrLou


People also ask

How do you replace all occurrences of a regex pattern in a string in Python?

The regex function re. sub(P, R, S) replaces all occurrences of the pattern P with the replacement R in string S . It returns a new string.

How do you replace multiple strings in Python?

Replace multiple different substrings There is no method to replace multiple different strings with different ones, but you can apply replace() repeatedly. It just calls replace() in order, so if the first new contains the following old , the first new is also replaced.

How do you replace and match in Python?

To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.

How do you change the exact string in Python?

Any string data can be replaced with another string in Python by using the replace() method. But if you want to replace any part of the string by matching a specific pattern then you have to use a regular expression.


1 Answers

You want re.sub() instead.

import re

def repl(var):
  return var.group().encode('rot13')

print re.sub('[aeiou]', repl, 'yesterday')

yrstrrdny

like image 185
Ignacio Vazquez-Abrams Avatar answered Sep 24 '22 14:09

Ignacio Vazquez-Abrams