Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the "(?<!…)" symbols mean in a Python regular expression?

I have the regular expression re.sub(r"(?<!\s)\}", r' }', string). What does the (?<!…) sequence indicate?

like image 776
Python Learner Avatar asked Jun 06 '17 16:06

Python Learner


2 Answers

It's a bit more than the < symbol, in the regular expression you've provided.

What's actually there is a 'Negative lookbehind': (?<! ) which is saying "What's before this is not...". In your case, it's looking for }, on the condition that what comes before it is not \s - whitespace (tabs, spaces...)

like image 124
Simon Fraser Avatar answered Oct 08 '22 10:10

Simon Fraser


Its a lookback. See the explanation here: http://www.rexegg.com/regex-disambiguation.html#negative-lookbehind

Quoted from the source:

Negative Lookbehind After the Match: \d{3}(?<!USD\d{3})
Explanation: \d{3} matches 100, then the negative lookbehind (?<!USD\d{3}) asserts that at that position in the string, what immediately precedes is not the characters "USD" then three digits.

like image 37
A.Kot Avatar answered Oct 08 '22 10:10

A.Kot