Python: 验证字符串是否代表有效的美国货币值?
Python: Verifying a string represents a valid US currency value?
如何验证字符串是否代表有效的美国货币值?
字符串可能完全由数字组成,也可能包含美元符号、逗号等。
上下文:我想验证一个字符串是否是正确的美元值,然后在删除或以其他方式处理非数字字符后将其转换为数字。
正则表达式
示例:$?(-?(\d+[,.])*\d+)
import re
re.match("$?(-?(\d+[,.])*\d+)", "$-12,000.01") # match
re.match("$?(-?(\d+[,.])*\d+)", "$-12,000.01").group(1) # extract matched value
>>> '-12,000.01'
re.sub('[,$]', '', '$-12,000.01') # remove comma and dollar sign
>>> '-12000.01'
float(re.sub('[,$]', '', '$-12,000.01')) # convert to float if the result doesn't contain any special character such as comma
>>> -12000.01
如果您的数据集中有更多案例,请将更多案例添加到正则表达式中。
可能有许多无效的边缘情况,例如 13.000,000
这个正则表达式将修复它:$?(-?\d*(\d+,)*\.?\d+)
。
因此,请根据需要添加任意数量的案例。
如何验证字符串是否代表有效的美国货币值?
字符串可能完全由数字组成,也可能包含美元符号、逗号等。
上下文:我想验证一个字符串是否是正确的美元值,然后在删除或以其他方式处理非数字字符后将其转换为数字。
正则表达式
示例:$?(-?(\d+[,.])*\d+)
import re
re.match("$?(-?(\d+[,.])*\d+)", "$-12,000.01") # match
re.match("$?(-?(\d+[,.])*\d+)", "$-12,000.01").group(1) # extract matched value
>>> '-12,000.01'
re.sub('[,$]', '', '$-12,000.01') # remove comma and dollar sign
>>> '-12000.01'
float(re.sub('[,$]', '', '$-12,000.01')) # convert to float if the result doesn't contain any special character such as comma
>>> -12000.01
如果您的数据集中有更多案例,请将更多案例添加到正则表达式中。
可能有许多无效的边缘情况,例如 13.000,000
这个正则表达式将修复它:$?(-?\d*(\d+,)*\.?\d+)
。
因此,请根据需要添加任意数量的案例。