首页 > 解决方案 > 如何在 Python 中使用正则表达式捕获数字?

问题描述

给定一个字母和数字的输入字符串,我试图捕获适合特定格式的数字。

输入样本如下:

你好,我的净资产是 1,000,000.00,我喜欢

预期产量:1,000,000.00

def detect_numbers(input_numbers_string):

number_format_pattern_map = {
        'us_start_with_decimal_regex': '(\.{1}\d+)$',
        'us_decimal_and_comma_regex': '\d{1,3}(,{1}\d{3})*(\.{1}\d+){0,1}$'
    }
    
fuzzy_matched_substrings = []
fuzzy_match_locations = []
fuzzy_changes = []
matched_formats = []

for numbers in number_format_pattern_map:
    number_pattern_string = number_format_pattern_map[numbers]
    r = regex.compile('(?e)(%s){e<=2}' % number_pattern_string)
    fuzzy_matches = r.finditer(query_string)
    for matches in fuzzy_matches:
         print(matches)

if __name__ == '__main__':
    query_string = 'hello my net worth is 1,000,000.00 and i like it'
    updated_query_string = detect_numbers(query_string)
    print(updated_query_string)

当我将“1,000,000.00”作为输入字符串传递时,我得到了预期的结果。但是,当我通过“你好,我的净资产是 1,000,000.00 并且我喜欢它”时,我得到以下结果:

regex.Regex('(?e)((\.{1}\d+)$){e<=2}', flags=regex.V0) <regex.Match object; span=(46, 48),match='it',fuzzy_counts=(2, 0, 0)> <regex.Match object; span=(48, 48), match='',fuzzy_counts=(0, 0, 2)> regex.Regex('(?e)(\d{1,3}(,{1}\d{3} ) (\.{1}\d+){0,1}$){e<=2}', flags=regex.V0) <regex.Match 对象;span=(47, 48), match='t', blur_counts=(1, 0, 0)> <regex.Match object; span=(48, 48), match='',fuzzy_counts=(0, 0, 1)> regex.Regex('(?e)((,{1}\d+)$){e<=2}' , flags=regex.V0) <regex.Match 对象;span=(46, 48),match='it',fuzzy_counts=(2, 0, 0)> <regex.Match object; span=(48, 48), match='',fuzzy_counts=(0, 0, 2)> regex.Regex('(?e)(\d{1,3}(\.{1}\d{3 })(,{1}\d+){0,1}$){e<=2}', flags=regex.V0) <regex.Match 对象;span=(47, 48), match='t', blur_counts=(1, 0, 0)> <regex.Match object; 跨度=(48, 48),匹配='',模糊计数=(0, 0, 1)>

这只会捕获它和 t,而它应该捕获 1,000,000.00 和类似的子字符串。任何帮助或提示表示赞赏。

标签: pythonregex

解决方案


图案

((?:\d{1,3},)*\d{1,3}\.\d{2})

解释

  • (启动主捕获组
    • (?:非捕获组(从匹配结果中忽略该组)
      • \d{1,3},一到三个数字后跟一个逗号。
    • )*非捕获组的结尾,*匹配零次或多次出现。这不是强制性的,值可以有逗号(超过 1,000)或低于 1,000(无逗号)。
    • \d{1,3}涵盖从 0 到 999 的值(这是强制性的)
    • \.\d{2}匹配.00通过.99
  • )结束主要捕获组

推荐阅读