Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python regex word repeat time

Tags:

python

regex

I got the following scenarios:

1) car collisions effect 3 right lanes
2) 3 car collisions effect right lanes

I want to figure out number of lanes instead of number of collision. To be specific I want extract number and "right lanes" with less than two \bwords\b in between.

\b(\d)<I want to limit 2 words here>\s*(lane[s]?)
OR
\b(\d)<I want to limit 10 characters here>\s*(lane[s]?)
like image 481
Edward Wang Avatar asked Jul 28 '26 06:07

Edward Wang


1 Answers

Using lookahead:

import re
s1 = "1) car collisions effect 3 right lanes"
s2 = "2) 3 car collisions effect right lanes"
print re.findall("(\d+)(?=(?:\s+\w+){,2}\s+right lanes)", s1) 
print re.findall("(\d+)(?=(?:\s+\w+){,2}\s+right lanes)", s2) 

Gives:

['3']
[]
like image 84
perreal Avatar answered Jul 30 '26 18:07

perreal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!