pythonpython-3.xregex

How can I find the last occurance of a dot not preceding with a slash?


I'm trying to create a regex to find the last dot in a string not preceded by a slash.

r = MyLine.Text.Swap\ Numbered\ and\ Unnumbered\ List.From\ -\ -\ -\ to\ Numbered\ list\ 1\.\ 2\.\ 3\.\ 

What I want to find as match is "From\ -\ -\ -\ to\ Numbered\ list\ 1\.\ 2\.\ 3\.\"

I tried to reverse the string but that didn't work either re.findall(".*\\.(?!\\\)", r[::-1])

What did I wrong?


Solution

  • You might use a negative lookbehind matching a dot, and then assert that what is to the left is not a \ followed by a dot.

    Then you could capture what comes after it in group 1 which would be returned by re.findall

    .*\.(?<!\\\.)(.*)
    

    See a regex demo and a Python demo

    For example:

    import re
    
    pattern = r".*\.(?<!\\\.)(.*)"
    
    r = "MyLine.Text.Swap\\ Numbered\\ and\\ Unnumbered\\ List.From\\ -\\ -\\ -\\ to\\ Numbered\\ list\\ 1\\.\\ 2\\.\\ 3\\.\\ "
    
    matches = re.findall(pattern, r)
    print(matches)
    

    Output

    ['From\\ -\\ -\\ -\\ to\\ Numbered\\ list\\ 1\\.\\ 2\\.\\ 3\\.\\ ']