您好,我想应用以下表达式来检查替换、插入、删除计数。然而 OR 语句似乎不起作用。正则表达式仅检查括号中的第一个语句。 例如:
correct_string = "20181201"
regex_pattern = r"((20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])){e}"
regex.fullmatch(regex_pattern, correct_string)
输出:
<regex.Match object; span=(0, 8), match='20181201', fuzzy_counts=(1, 0, 0)>
它说由于第 5 位数字而有一个替换,但是如果在 OR 语句中它存在
另一个例子:
correct_string = "20180201"
regex_pattern = r"((20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])){e}"
regex.fullmatch(regex_pattern, correct_string)
输出:
<regex.Match object; span=(0, 8), match='20180201'>
在这种情况下,它表示没有替换,根据 OR 中的第一个语句,这是正确的。
我该如何解决这个问题。谢谢。
最佳答案
您需要使用regex.ENHANCEMATCH
:
By default, fuzzy matching searches for the first match that meets the given constraints. The
ENHANCEMATCH
flag will cause it to attempt to improve the fit (i.e. reduce the number of errors) of the match that it has found.
Python 演示:
import regex
correct_string = "20181201"
regex_pattern = r"((20[0-9]{2})(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])){e}"
print(regex.fullmatch(regex_pattern, correct_string, regex.ENHANCEMATCH))
// => <regex.Match object; span=(0, 8), match='20181201'>
请参阅online Python demo .
关于Python 正则表达式 : OR statement does not work in regex module,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53727711/