Python 模式替换
我是一个RegEx新手,仍然接受模式匹配。但我试图理解模式替换。我希望改变句子中的货币模式,其中的值可以是任何东西,也可以是不可预测的,但始终采用以下格式:Python 模式替换,python,regex,pattern-matching,Python,Regex,Pattern Matching,我是一个RegEx新手,仍然接受模式匹配。但我试图理解模式替换。我希望改变句子中的货币模式,其中的值可以是任何东西,也可以是不可预测的,但始终采用以下格式: <currency_symbol><number><number><dot><number><number><letter> 致: 我已设法匹配模式,但未替换: >>> import re >>> sent = "mr
<currency_symbol><number><number><dot><number><number><letter>
致:
我已设法匹配模式,但未替换:
>>> import re
>>> sent = "mr x is worth $44.4m and mr y is worth $59.1m"
>>> print(re.findall(r'\$\d+\.\d+\m', sent))
['$44.4m', '$59.1m']
如何实现正则表达式模式替换?或者有比regex更好的方法吗?最简单的替代方法是使用函数来替换
repl
:
>>> import re
>>> source = 'mr x is worth $44.4m and mr y is worth $59.1m'
>>> def sub_func(match):
"""Convert the match to the new format."""
string = match.group(0)
millions = int(float(string[1:-1]) * 1000000)
return '${:d}'.format(millions)
>>> re.sub(r'\$\d+\.\d+m', sub_func, source)
'mr x is worth $44400000 and mr y is worth $59100000'
您可以使用
'${:,d}'。格式(百万)
来获取例如'$44400000'
使用re.sub()
有什么问题?
>>> import re
>>> sent = "mr x is worth $44.4m and mr y is worth $59.1m"
>>> print(re.findall(r'\$\d+\.\d+\m', sent))
['$44.4m', '$59.1m']
>>> import re
>>> source = 'mr x is worth $44.4m and mr y is worth $59.1m'
>>> def sub_func(match):
"""Convert the match to the new format."""
string = match.group(0)
millions = int(float(string[1:-1]) * 1000000)
return '${:d}'.format(millions)
>>> re.sub(r'\$\d+\.\d+m', sub_func, source)
'mr x is worth $44400000 and mr y is worth $59100000'