【发布时间】:2020-08-01 02:48:45
【问题描述】:
我正在尝试使用正则表达式和 1 个替换、插入或删除的错误距离来更正输入字符串。
My input string is: 1 00.00000000%]
My expected output is: 100.00000000%]
The regex I am using is: (?<![\S])[1-9]\d{0,2}(?:,\d{3})*(?:\.\d+)?%?(?!\S)
由于我正在尝试的代码,它似乎没有找到 1 00.00000000% 作为模糊匹配,而是找到 1、00 和 .00000000% 作为 3 个单独的匹配。我的做法如下:
number_format_pattern_map = {
'us_decimal_and_comma_regex': '(?<![\S])[1-9]\d{0,2}(?:,\d{3})*(?:\.\d+)?%?(?!\S)'
}
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]
substitution = regex.compile('(%s){s<=1}' % number_pattern_string)
insertion = regex.compile('(%s){i<=1}' % number_pattern_string)
deletion = regex.compile('(%s){d<=1}' % number_pattern_string)
substitution_matches = list(substitution.finditer(input_numbers_string))
insertion_matches = list(insertion.finditer(input_numbers_string))
deletion_matches = list(deletion.finditer(input_numbers_string))
fuzzy_matches = substitution_matches
for match in insertion_matches:
if match not in fuzzy_matches:
fuzzy_matches.append(match)
for match in deletion_matches:
if match not in fuzzy_matches:
fuzzy_matches.append(match)
for fuzzy_match in fuzzy_matches:
fuzzy_match_substring = fuzzy_match.group()
fuzzy_match_location = list(fuzzy_match.span())
fuzzy_change = list(fuzzy_match.fuzzy_changes)
根据我上面的代码,当我打印fuzzy_match_substring 时,它应该显示所有匹配的子字符串。在这一点上,我会选择最相关的一个并进行更改(删除一个空格)。
但是,当我打印模糊匹配子字符串时,我没有得到所需的子字符串 (1 00.00000000%),而是得到以下内容:
1
1
1
00
.00000000%
0.00000000%
1
00
.00000000%
但是,当我删除字符串末尾的方括号时,我得到了所需的子字符串。
我的问题是,我怎样才能找到以下模糊匹配 1 00.00000000% 与索引 1 处的替换或插入的相应 1 错误界限。谢谢您的帮助!
【问题讨论】:
-
我在理解您的问题时遇到了一些麻烦。你只是想删除空白空间吗?你能发布一些其他输入/输出组合的例子吗?
-
没错..最终我想删除空格,但正则表达式编译器无法识别使用替换、插入或删除的正确子字符串,所以我无法删除它。