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

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

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

  1. "'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如下:

  1. import re
  2. strs = ["'Super-rainbow' time to fight - 22-50t",
  3. "'m-m-m' title destroyer - 20t",
  4. "'eating food' spaghetti - 5-6 times",
  5. "'hype-time' john cena -ttl",
  6. "cat-food time - 25-26p"]
  7. for s in strs:
  8. last = re.split(r' - ', s)[-1]
  9. print(f"{s}:{last}")

图纸:

  1. 'Super-rainbow' time to fight - 22-50t:22-50t
  2. 'm-m-m' title destroyer - 20t:20t
  3. 'eating food' spaghetti - 5-6 times:5-6 times
  4. 'hype-time' john cena -ttl:'hype-time' john cena -ttl
  5. cat-food time - 25-26p:25-26p
展开查看全部
e0uiprwp

e0uiprwp2#

如果你的文章和你写的一样。您的文本将被解释为一个元组。
您可以使用str.split()str.rsplit()而不使用正则表达式

  1. 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"
  2. print(txt)
  3. #
  4. ("'Super-rainbow' time to fight - 22-50t",
  5. "'m-m-m' title destroyer - 20t",
  6. "'eating food' spaghetti - 5-6 times",
  7. "'hype-time' john cena -ttl",
  8. "cat-food time - 25-26p")
  1. [x.rsplit(' -')[1] for x in txt]
  2. #[' 22-50t', ' 20t', ' 5-6 times', 'ttl', ' 25-26p']

相关问题