Huzaifa Qamer
Huzaifa Qamer

Reputation: 314

Negative lookbehind is not matching

Considering text = "car price is $2017 and manufactured in 2017 and make is Honda", I am trying to write a regex that matches the second 2017 (the manufacturing year). For that I am using negative lookbehind pattern but the string being matched is always the first 2017.

The code I am using is re.search('(?<!\$)2017', text).group() and have also used re.search('(?<!$)2017', text).group() (without \) but no success.

Any pointers to what I am doing wrong.

Upvotes: 0

Views: 53

Answers (2)

Chen A.
Chen A.

Reputation: 11280

What you are missing is the r, which indicates raw string

>>> re.search(r'(?<!\$)2017', text).group()
'2017'

Adding that and your code works.

Upvotes: 0

anubhava
anubhava

Reputation: 785058

You don't need a negative lookbehind to match 2nd instance of 2017.

You can use non-greedy quantifier:

^.*?2017.*?(2017)

RegEx Demo

Second instance is captured in group no. 1

Code:

>>> str = 'car price is $2017 and manufactured in 2017 and make is Honda'
>>> print re.findall(r'^.*?2017.*?(2017)', str)
['2017']

Upvotes: 1

Related Questions