Python中使用re.search()正则表达式匹配失败问题求助
解决提取$200子串的问题
问题根源
你当前的代码有两个问题导致匹配失败:
- 语法错误:
re.search的参数顺序写错了,正确格式是re.search(正则表达式, 目标字符串),你把line写进了正则参数里,这是无效写法。 - 正则匹配范围限制:
^表示匹配行首,若目标行的$前存在空白(比如缩进、换行残留空格),或者你想匹配的内容不在行首,就会匹配失败。
修正后的解决方案
方案1:提取带$的完整子串
直接匹配$后跟数字的组合,不限制行首位置,适配更多场景:
import re text = """Autorización 28 MAY 2024, 20:34 (hora de CDMX) $200.oo Monto """ for line in text.splitlines(): match = re.search(r'\$\d+', line) if match: monto = match.group(0) print(monto) # 输出结果:$200
方案2:仅提取数字部分
如果只需要200这个数字,可以用捕获组:
for line in text.splitlines(): match = re.search(r'\$(\d+)', line) if match: monto_num = match.group(1) print(monto_num) # 输出结果:200
方案3:严格匹配行首的$(确保无前置空白)
如果确定目标行一定以$开头,可保留^:
for line in text.splitlines(): match = re.search(r'^\$\d+', line) if match: monto = match.group(0) print(monto)
内容的提问来源于stack exchange,提问作者Alexis Mora
相关产品推荐
相关产品推荐

