有没有办法使用正则表达式或任何类似方法从 python 中的字符串后面搜索?

Is there a way to search from the back of a string in python using regex or any similar method?

提问人:Matthew Smith 提问时间:10/5/2023 最后编辑:Goku - stands with PalestineMatthew Smith 更新时间:10/5/2023 访问量:83

问:

我的文本可以采用多种不同的形式,其中包含破折号。例子:

"'Super-rainbow' time to fight - 22-50t", "'m-m-m' title destroyer - 20t", "'eating food' spaghetti - 5-6 times", "'hype-time' john cena -ttl", "cat-food time - 25-26p".

我想从接近结尾的破折号后面取走所有字符。如。在python中有什么好方法可以做到这一点吗?"22-50t", "20t", "5-6 times", "-ttl" , "25-26p

python-3.x 正则表达式 字符串

评论

0赞 Marco F. 10/5/2023
也许拆分字符串(按空格)并从末尾开始搜索列表
1赞 Goku - stands with Palestine 10/5/2023
在有没有多余的空间?john cena -ttljohn cena - ttl
1赞 Barmar 10/5/2023
使用以 .$
1赞 Barmar 10/5/2023
这是一个文本(其中包含文字)还是字符串列表?如果是一个列表,它在哪里?"[]
1赞 tdelaney 10/5/2023
这里有一套明确的规则吗?我可以写一个正则表达式,让大部分内容正确。但是,为什么“-ttl”是结果而不是“-20 t”呢?我们怎么知道破折号什么时候不应该成为答案的一部分?

答:

0赞 Timur Shtatland 10/5/2023 #1

像这样使用 re.split

import re

strs = ["'Super-rainbow' time to fight - 22-50t",
        "'m-m-m' title destroyer - 20t",
        "'eating food' spaghetti - 5-6 times",
        "'hype-time' john cena -ttl",
        "cat-food time - 25-26p"]

for s in strs:
    last = re.split(r' - ', s)[-1]
    print(f"{s}:{last}")

指纹:

'Super-rainbow' time to fight - 22-50t:22-50t
'm-m-m' title destroyer - 20t:20t
'eating food' spaghetti - 5-6 times:5-6 times
'hype-time' john cena -ttl:'hype-time' john cena -ttl
cat-food time - 25-26p:25-26p
0赞 Goku - stands with Palestine 10/5/2023 #2

如果您的文本与您发布的一样。您的文本将被解释为元组。

您可以在没有正则表达式的情况下使用 或str.split()str.rsplit()

txt = "'Super-rainbow' time to fight - 22-50t", "'m-m-m' title destroyer - 20t", "'eating food' spaghetti - 5-6 times", "'hype-time' john cena -ttl", "cat-food time - 25-26p"

print(txt)

#
 ("'Super-rainbow' time to fight - 22-50t",
 "'m-m-m' title destroyer - 20t",
 "'eating food' spaghetti - 5-6 times",
 "'hype-time' john cena -ttl",
 "cat-food time - 25-26p")

[x.rsplit(' -')[1] for x in txt]

#[' 22-50t', ' 20t', ' 5-6 times', 'ttl', ' 25-26p']

评论

0赞 Error - Syntactical Remorse 10/5/2023
从技术上讲,性能会更高。rsplitmaxsplit=1
0赞 Goku - stands with Palestine 10/5/2023
@Error-SyntacticalRemorse 谢谢..已编辑:) ;stackoverflow.com/questions/21103433/......