python - 如何获取仅匹配和包含部分的正则表达式匹配索引?

标签 python python-3.x regex

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/

相关文章:

python - 文本中的日期列表

Python 解析 XML 文件中的某些行并将该行输出到文本小部件

python - Python中的多个字符串替换

python - 如何在 python 3 中找到笛卡尔元素的总和?

javascript - 用于匹配重音字符的正则表达式

python - python 正则表达式字符集中的反斜杠(如何指定 'not a backslash' 字符集)?

Ruby 正则表达式不匹配

python - 将 zip 文件中的固定宽度文本文件读取到 Pandas 数据框中

python - Numpy 安全编程

python - 从循环内的 a.href 获取数据