如何在Python中通过一次替换、插入或删除来更正regex



我正在尝试使用正则表达式和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时,它应该显示所有匹配的子字符串。在这一点上,我会选择最相关的一个并进行更改(删除一个空格(。

然而,当我打印fuzzy_match_substring时,我没有得到所需的子字符串(1 00.00000000%(,而是得到以下内容:

1
1
1
00
.00000000%
0.00000000%
1
00
.00000000%

然而,当我移除字符串末尾的方括号时,我得到了所需的子字符串。

我的问题是,我如何找到以下模糊匹配1 00.00000000%与索引1处的替换或插入的相应1误差界。谢谢你的帮助!

如果您只想删除输入中的空白,那么使用简单的regex:很容易

from re import sub
x = input("Value: ")
x = sub(r"s", "", x)
print(x)

如果您写入1 00.00000000%],它将返回100.00000000%]

解释

正则表达式s匹配任何空格,然后我们只使用re.sub将匹配项替换为空字符串。

最新更新