首页 > 解决方案 > 使用正则表达式删除子字符串

问题描述

我需要编写一个正则表达式来从下面的字符串中提取末尾的金额

输入: Total: 4.00 4,123.00

输出应该像:Total: 4,123.00

这意味着我需要用它删除“4.00”。

我的python代码:

import re
text = 'Total: 4.00 4,123.00'

m = re.search('4.00 (.+?)$', text)
if m:
    found = m.group(1)
    print(found)

但是这个正则表达式也删除Total: 了。我该如何解决?

标签: pythonstring

解决方案


我会在这里使用 split 并避免使用正则表达式:

inp = "Total: 4.00 4,123.00"
parts = inp.split()
output = parts[0] + ' ' + parts[2]
print(output)  # Total: 4,123.00

推荐阅读