我需要在我的文本中構建一個正則運算式的所有匹配項以及它們在其中的開始和結束位置的串列。
雖然 re.search 回傳一個匹配物件,我可以利用 match.start 和 match.end 屬性,但 re.findall 似乎只回傳匹配字串的串列,但沒有匹配物件。
下面是一些代碼來演示:
import re
text = "40 boxed and 25 crates weight 254 pounds and occupy 23 cubic feet."
searchfor = r"(\d )"
match = re.search(searchfor, text)
if match:
print(f"Pattern {match.group()} found at {match.start()} until {match.end()}")
matches = re.findall(searchfor, text)
for match in matches:
# print(f"Pattern {match.group()} found at {match.start()} until {match.end()}")
print(match)
感謝您的任何見解。2022年快樂
uj5u.com熱心網友回復:
re.finditer() 正是你要找的:
matches = re.finditer(searchfor, text)
for match in matches:
print(f"Pattern {match.group()} found at {match.start()} until {match.end()}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401256.html
