JavaScript
x
3
1
txt = 'Port of Discharge/ Airport of destinationtXYZABCtttttttt44B'
2
3
I am doing:
JavaScript
1
9
1
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)]
2
3
print(reg_ind)
4
[(0, 56)]
5
6
print(txt[reg_ind[0][0]: reg_ind[0][1]])
7
Port of Discharge/ Airport of destination XYZABC
8
9
I want the index to end at Airport of destination.
Desired output:
JavaScript
1
6
1
print(reg_ind)
2
[(0, 41)]
3
4
print(txt[reg_ind[0][0]: reg_ind[0][1]])
5
Port of Discharge/ Airport of destination
6
Advertisement
Answer
You may move .*
into the lookahead to avoid consuming that part of the match:
JavaScript
1
3
1
port.{0,6}discharge.{0,3}/.{0,3}airport.{0,7}destination(?=.*44B)
2
^^^^^^^^
3
See a regex demo and a Python demo:
JavaScript
1
7
1
import re
2
3
txt = 'Port of Discharge/ Airport of destinationtXYZABCtttttttt44B'
4
pat = r' port.{0,6}discharge.{0,3}/.{0,3}airport.{0,7}destination(?=.*44B)'
5
reg_ind = [(m.start(0),m.end(0)) for m in re.finditer(pat, txt,re.IGNORECASE | re.VERBOSE)]
6
print(reg_ind) # => [(0, 41)]
7