You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:如何从字符串末尾反向搜索并提取短横线后内容?

提取字符串末尾短横线后的内容(Python实现)

需求说明

给定一批带短横线的字符串:

"'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")
  • 若短横线后直接跟内容,提取短横线及后面的所有内容(如"-ttl")

实现方法

方法一:正则表达式

利用正则锚定字符串结尾,匹配最后一个短横线及后续内容,通过分支处理两种情况:

import re

target_strings = [
    "'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"
]

# 正则分支:匹配" - 内容"或"-内容"两种格式
pattern = re.compile(r'-(?:\s+)(.*)$|-(.*)$')
for s in target_strings:
    match_result = pattern.search(s)
    if match_result:
        # 优先取空格后的内容,没有则取短横线+后续内容
        final_result = match_result.group(1) if match_result.group(1) else '-' + match_result.group(2)
        print(final_result)

运行结果完全符合需求:

22-50t
20t
5-6 times
-ttl
25-26p

方法二:字符串反向查找(无需正则)

用rfind()方法从字符串末尾反向定位最后一个短横线的位置,再根据后续字符处理:

target_strings = [
    "'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 target_strings:
    dash_pos = s.rfind('-')
    if dash_pos != -1:
        after_dash = s[dash_pos+1:]
        # 判断短横线后是否是空格
        if after_dash.startswith(' '):
            print(after_dash.strip())
        else:
            print('-' + after_dash)

该方法逻辑直观,适合不想用正则的场景。

关于反向搜索的问题

Python完全支持从字符串末尾反向搜索的需求:

  • 字符串方法rfind()、rindex()都是从末尾开始查找指定字符/子串的位置
  • 正则表达式可以通过锚定结尾($)来匹配字符串末尾的内容,本质也是从后往前匹配的逻辑

内容的提问来源于stack exchange,提问作者Matthew Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:37:11