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

如何用Python Regex保留首尾含$的数字并实现求和?

解决方案

1. 正则匹配提取目标金额

用正则表达式精准匹配以$开头或以$结尾的数字串,正则表达式为:(\$\d+|\d+\$)

  • \$\d+:匹配$后接一串数字的格式(如$4000、$1000)
  • \d+\$:匹配一串数字后接$的格式(如5000$、200$)
  • |:逻辑或,同时匹配两种格式
  • 括号用于分组提取完整匹配项

2. 代码实现(以Python为例)

import re

# 原始文本
raw_text = """-MacBook 2018 $4000 
-Apple watch S3
-11 5000$ 1000Islands iphone$1000 200$airpods"""

# 提取所有符合要求的金额字符串
target_amounts = re.findall(r'(\$\d+|\d+\$)', raw_text)
# 清理$符号并转换为整数求和
total_sum = sum(int(amt.replace('$', '')) for amt in target_amounts)

# 输出结果
print("提取到的目标金额:", target_amounts)  # 输出:['$4000', '5000$', '$1000', '200$']
print("总金额:", total_sum)  # 输出:7200

3. 其他语言示例(JavaScript)

const rawText = `-MacBook 2018 $4000 
-Apple watch S3
-11 5000$ 1000Islands iphone$1000 200$airpods`;

// 匹配目标金额
const targetAmounts = rawText.match(/(\$\d+|\d+\$)/g);
// 计算总和
const totalSum = targetAmounts.reduce((acc, amt) => acc + parseInt(amt.replace('$', '')), 0);

console.log("提取到的目标金额:", targetAmounts);
console.log("总金额:", totalSum);

关键说明

  • 该正则会自动过滤掉不带$的数字(如2018、11、1000Islands中的1000),完全符合期望结果
  • 处理逻辑高效:正则匹配是线性扫描,后续的转换求和也是O(n)时间复杂度,适合批量文本处理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:22:12