txt = 'Port of Discharge/ Airport of destination\tXYZABC\t\t\t\t\t\t\t\t44B'
我正在做:
reg_ind = [(m.start(0),m.end(0)) for m in re.finditer(r' port.{0,6}discharge.{0,3}/.{0,3}airport.{0,7}destination.*(?=44B)', txt,re.IGNORECASE | re.VERBOSE)]
print(reg_ind)
[(0, 56)]
print(txt[reg_ind[0][0]: reg_ind[0][1]])
Port of Discharge/ Airport of destination XYZABC
我希望索引以目的地机场结束。
期望的输出:
print(reg_ind)
[(0, 41)]
print(txt[reg_ind[0][0]: reg_ind[0][1]])
Port of Discharge/ Airport of destination
最佳答案
您可以将 .*
移动到前瞻中以避免消耗匹配的该部分:
port.{0,6}discharge.{0,3}/.{0,3}airport.{0,7}destination(?=.*44B)
^^^^^^^^
查看regex demo和一个Python demo :
import re
txt = 'Port of Discharge/ Airport of destination\tXYZABC\t\t\t\t\t\t\t\t44B'
pat = r' port.{0,6}discharge.{0,3}/.{0,3}airport.{0,7}destination(?=.*44B)'
reg_ind = [(m.start(0),m.end(0)) for m in re.finditer(pat, txt,re.IGNORECASE | re.VERBOSE)]
print(reg_ind) # => [(0, 41)]
关于python - 如何获取仅匹配和包含部分的正则表达式匹配索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59981539/