如何使用Python的finditer替换每个匹配的字符串?

8 投票
1 回答
6826 浏览
提问于 2025-04-16 19:52

我正在使用Python(实际上是pl/python)来在一个非常大的文本对象中,逐步找到一系列的正则表达式匹配。这一切都运行得很好!每次匹配都是不同的结果,每次替换也会是不同的结果,最终会根据循环中的查询来决定。

目前,我只想用任何文本替换rx中的每一个匹配项,这样我就能理解它是如何工作的。有人能给我一个明确的例子,说明如何替换匹配到的文本吗?

match.group(1)似乎正确地指示了匹配到的文本;这样做是对的吗?

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 )  ------------------------------

1 个回答

10

你需要使用 re.sub() 这个函数。

import re

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

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

yrstrrdny

撰写回答