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

如何在Python正则表达式中匹配含斜杠/的字符串并返回布尔值

解决Python正则匹配'/story/'的问题

如果你是要检查URL中包含'/story/'这个子串,直接用re.search就能实现,返回布尔值的代码如下:

import re

def has_story_path(url):
    # 用bool()把匹配结果转成True/False
    return bool(re.search(r'/story/', url))

# 测试示例
print(has_story_path("https://example.com/story/123"))  # 输出True
print(has_story_path("https://example.com/article/456"))  # 输出False

如果需要精确匹配整个URL就是'/story/',用re.fullmatch来确保字符串完全符合:

import re

def is_exact_story_url(url):
    return bool(re.fullmatch(r'/story/', url))

# 测试示例
print(is_exact_story_url("/story/"))  # 输出True
print(is_exact_story_url("/story/123"))  # 输出False

常见失败原因说明

之前匹配失败大概率是这两个原因:

  • 误用了re.match:它只从字符串开头开始匹配,如果URL不是以'/story/'开头,就会返回None。改用re.search可以在整个字符串里查找匹配项。
  • 没必要的转义:斜杠/在Python正则里不是特殊字符,不需要写成\/,直接写/story/就可以匹配。

内容的提问来源于stack exchange,提问作者Jeremiah Taylor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:45:37