Python 正则表达式 : OR statement does not work in regex module

标签 python regex

您好,我想应用以下表达式来检查替换、插入、删除计数。然而 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/

相关文章:

python - 使用正则表达式从另一个列表中选择列表

Python:大文件上的正则表达式。简单的方法?

python - 在python中设置可变数量的输入节点

javascript - 正则表达式中的括号单位返回额外的匹配项

regex - 使用 nginx proxy_pass 修改 Location header

python - 在运行时在 Python 3 中动态加载模块

android - 使用 Kivy 访问 Android 相机时出现错误

python - 从文件 python 创建字典

regex - Tesseract OCR 力模式

regex - 取出字符串部分和字符串的数字部分