【问题标题】:using python finditer, how can I replace each matched string?使用 python finditer,如何替换每个匹配的字符串?
【发布时间】:2011-06-20 01:53:34
【问题描述】:

我正在使用 Python(实际上是 pl/python)在一个非常大的文本对象中连续查找一系列正则表达式匹配项。这工作正常!每次匹配都是不同的结果,每次替换都会是不同的结果,最终基于循环内的查询。

目前,我很乐意将 rx 中的每个匹配项替换为 any 文本,以便我了解它是如何工作的。有人可以给我一个替换匹配文本的明确示例吗?

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

【问题讨论】:

    标签: python iterator plpython


    【解决方案1】:

    你想要re.sub()

    import re
    
    def repl(var):
      return var.group().encode('rot13')
    
    print re.sub('[aeiou]', repl, 'yesterday')
    

    yrstrrdny

    【讨论】:

    • Ignacio - 好的,谢谢 - 我现在正在尝试 re.sub(),取得了一些成功。但是我如何对匹配进行子字符串搜索,以提取我需要的一点?
    • 函数将通过match object
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2011-10-23
    • 1970-01-01
    • 2014-03-12
    • 2016-10-20
    • 2016-09-26
    相关资源
    最近更新 更多