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

正则匹配版本号失败求助:re.match返回None如何解决?

解决正则匹配版本号返回None的问题

问题原因

你要匹配的目标字符串是'9.0.1 and earlier\n\n\n\n\n',但你用的正则r'^[0-9].[0-9]*$'要求整个字符串完全符合「数字+任意字符+任意数字」的格式,可目标字符串包含首尾换行、空格,还有and earlier这类额外文本,自然匹配失败返回None。

解决步骤

1. 先清理字符串首尾空白

用strip()方法去掉目标字符串首尾的换行、空格等空白内容,得到干净的'9.0.1 and earlier'。

2. 调整正则匹配需求内容

根据你的实际需求选择对应写法:

  • 只提取纯版本号(比如9.0.1):
import re

ree1 = ['\nmultiple cross-site scripting (xss) vulnerabilities in', '9.0.1 and earlier\n\n\n\n\n']
# 清理首尾空白
cleaned_str = ree1[1].strip()
# 匹配三段式版本号
version_match = re.match(r'^\d+\.\d+\.\d+', cleaned_str)
if version_match:
    print(version_match.group())  # 输出:9.0.1
  • 直接从原字符串提取版本号(跳过手动清理):
version_match = re.search(r'\d+\.\d+\.\d+', ree1[1])
if version_match:
    print(version_match.group())  # 输出:9.0.1
  • 匹配包含and earlier的完整版本描述:
cleaned_str = ree1[1].strip()
full_match = re.match(r'^\d+\.\d+\.\d+ and earlier$', cleaned_str)
if full_match:
    print(full_match.group())  # 输出:9.0.1 and earlier

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:01:20