最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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\\.\\ ']
发布评论

评论列表(0)

  1. 暂无评论