4
我正在使用Python(pl/python,實際上)在一個非常大的文本對象中連續查找一系列正則表達式匹配。這工作正常!每個匹配是一個不同的結果,每個替換將是一個不同的結果,最終基於循環內的查詢。使用python finditer,我怎樣才能替換每個匹配的字符串?
目前,我很樂意用任何文字替換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) ------------------------------
伊格納西奧 - OK,TKS這個 - 現在我想應用re.sub(),取得了一些成功。但是,我如何在匹配中搜索子字符串,以便抽出一些我需要的信息? – DrLou
該函數將傳遞[match object](http://docs.python.org/library/re.html#match-objects) –