Как получить индекс соответствия регулярному выражению только совпадающей и включенной части? - PullRequest
1 голос
/ 30 января 2020
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

1 Ответ

2 голосов
/ 30 января 2020

Вы можете переместиться .* в сторону просмотра, чтобы избежать потребления этой части матча:

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

См. Демо regex и демо Python :

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)]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...