“\z"锚在 Python 正则表达式中不起作用 [英] The "\z" anchor not working in Python regex

查看:71
本文介绍了“\z"锚在 Python 正则表达式中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下面的正则表达式,

I have a below regex expression,

/\A(\d{5}[A-Z]{2}[a-zA-Z0-9]{3,7}-TMP|\d{5}[A-Z]{2}\d{3,7}(\-?\d{2})*)\z/

我正在检查以下字符串.我猜第一个和第三个应该返回一个匹配项,第二个返回一个不匹配项.但是我没有在所有 3 个上都匹配.我的正则表达式有错吗?

I am checking against below strings. The first and third should return a match I guess and second a no match. But I am not getting a match on all 3. Is my regex wrong?

99844RI1800001
99806CAAUSJ-TMP1
99844RI1800002

推荐答案

Python re 不支持 \z,支持 \Z作为匹配字符串末尾的等效模式.您的模式需要文字 z 字符出现在模式的末尾.

Python re does not support \z, it supports \Z as equivalent pattern matching the very end of the string. Your pattern requires the literal z char to be there at the end of the pattern.

参见 Rexegg.com 参考:

✽ 在 Python 中,标记 \Z\z 在其他引擎中的作用相同:它只匹配字符串的最末尾.

✽ In Python, the token \Z does what \z does in other engines: it only matches at the very end of the string.

因此你可以使用

\A(\d{5}[A-Z]{2}[a-zA-Z0-9]{3,7}-TMP|\d{5}[A-Z]{2}\d{3,7}(-?\d{2})*)\Z

查看正则表达式演示

请注意,从 Python 3.6 开始,您甚至会遇到异常:

Note that starting with Python 3.6 you would even get an exception:

re.error: bad escape \z at position 68

请参阅 Python re 文档:

See Python re docs:

在 3.6 版更改:由 '\' 和 ASCII 字母组成的未知转义现在是错误.

Changed in version 3.6: Unknown escapes consisting of '\' and an ASCII letter now are errors.

这篇关于“\z"锚在 Python 正则表达式中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆