提问人:Matthew Smith 提问时间:10/5/2023 最后编辑:Goku - stands with PalestineMatthew Smith 更新时间:10/5/2023 访问量:83
有没有办法使用正则表达式或任何类似方法从 python 中的字符串后面搜索?
Is there a way to search from the back of a string in python using regex or any similar method?
问:
我的文本可以采用多种不同的形式,其中包含破折号。例子:
"'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
答:
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
从技术上讲,性能会更高。rsplit
maxsplit=1
0赞
Goku - stands with Palestine
10/5/2023
@Error-SyntacticalRemorse 谢谢..已编辑:) ;stackoverflow.com/questions/21103433/......
评论
john cena -ttl
john cena - ttl
$
"
[]