Philipp Braun Philipp Braun - 2 months ago 4x
Python Question

Regex match inner '.'

I would like to remove an inner sentence based on one word. So instead of just 'start' I would like the regex statement to return 'start.stop.'.

>>> import re
>>> s = ' nice.'
>>> re.sub(r'\..*nice.*', '', s)


You need a negated character class instead of .* to refuse of matching the dots in other sentences. And in order to preserving the last dot, you can use a positive-lookahead for the last dot, to makes the regex engine doesn't capture that (just check its existence).

>>> re.sub(r'\.[^.]*nice[^.]*(?=\.)', '', s)

Another good example by @bfontaine:

>>> s = ""
>>> re.sub(r'\.[^.]*nice[^.]*(?=\.)', '', s)