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

匹配百分比中纯数字的Python正则表达式(支持逗号/小数点)

解决方案:提取百分比中的纯数字内容

核心思路是先匹配出百分比符号前的完整数字序列(支持点或逗号作为小数分隔符),再移除其中的非数字字符,得到纯数字结果。

正则表达式说明

使用正则 (\d+(?:[.,]\d+)?)(?=%) 匹配目标数字段:

  • \d+:匹配至少一位整数数字
  • (?:[.,]\d+)?:非捕获组,匹配可选的小数部分(点/逗号 + 至少一位数字),?表示该部分可省略
  • (?=%):正向预查,确保匹配的数字段紧跟在%符号前

Python 代码示例

import re

# 测试用例
test_strings = [
    "a good 98.15% play",
    "a good 98,15% play",
    "a good 100% play",
    "a good 98% play"
]

# 编译正则表达式
num_pattern = re.compile(r'(\d+(?:[.,]\d+)?)(?=%)')

for s in test_strings:
    match_result = num_pattern.search(s)
    if match_result:
        # 移除匹配结果中的点或逗号,得到纯数字
        pure_num = re.sub(r'[.,]', '', match_result.group(1))
        print(f"{s} → {pure_num}")

运行后输出:

a good 98.15% play → 9815
a good 98,15% play → 9815
a good 100% play → 100
a good 98% play → 98

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:35:15