python - How can I find the last occurance of a dot not preceding with a slash? - Stack Overflow

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

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?

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?

Share Improve this question asked Nov 16, 2024 at 18:50 RemanReman 8,13911 gold badges60 silver badges98 bronze badges 2
  • Are you SURE the string actually contains backslashes? It is easy to be fooled by string escapes. And as it is, there are NO dots in that string not preceded by a backslash. – Tim Roberts Commented Nov 16, 2024 at 18:53
  • Please provide the code you use to define the example string, run the regex and display the result. Note that the assignment to r is not valid Python. – trincot Commented Nov 16, 2024 at 19:16
Add a comment  | 

1 Answer 1

Reset to default 3

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\\.\\ ']

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745646822a4638018.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信