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 ) ------------------------------
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.
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.
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.
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.
You want re.sub()
instead.
import re
def repl(var):
return var.group().encode('rot13')
print re.sub('[aeiou]', repl, 'yesterday')
yrstrrdny
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With