【问题标题】:How to get index of regex match of only the matched and included part?如何仅获取匹配和包含部分的正则表达式匹配索引?
【发布时间】:2020-01-30 08:13:06
【问题描述】:
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

【问题讨论】:

  • 我的解决方案有帮助吗?如果您需要更多帮助,请告知。
  • 是的 Wiktor,它对我提出的问题有所帮助。谢谢。
  • 很高兴它对你有用。如果我的回答对您有帮助,请考虑接受the answer 并点赞。

标签: python python-3.x regex


【解决方案1】:

您可以将.* 移动到前瞻中以避免消耗匹配的那部分:

port.{0,6}discharge.{0,3}/.{0,3}airport.{0,7}destination(?=.*44B)
                                                         ^^^^^^^^

查看regex demoPython 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)]

【讨论】:

    猜你喜欢
    • 2013-10-12
    • 1970-01-01
    • 2021-02-09
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    相关资源
    最近更新 更多