Search code examples
pythonregexregex-lookaroundsnegative-lookbehind

Combine negative lookahead and behind regex


I would like a regex which will split a string at every "." except if the "." is preceded AND followed by an number. example:

"hello world.foo 1.1 bar.1" ==> ["hello world","foo 1.1 bar", "1"]

I currently have:

"(?<![0-9])\.(?!\d)" 

but it gives:

["hello world", "foo 1.1 bar.1"]

but its not finding the last "." valid.


Solution

  • Split on . if it is not preceded by a digit, or if it is not succeeded by a digit:

    In [18]: re.split(r'(?<!\d)\.|\.(?!\d)', text)
    Out[18]: ['hello world', 'foo 1.1 bar', '1']