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

tvz2xvvm  于 2023-10-22  发布在  Python
关注(0)|答案(2)|浏览(114)

我有文本,可以采取多种不同的形式与破折号在他们。示例如下:

"'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".

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

zxlwwiss

zxlwwiss1#

使用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
e0uiprwp

e0uiprwp2#

如果你的文章和你写的一样。您的文本将被解释为一个元组。
您可以使用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']

相关问题