在 python 正则表达式中使用锚点来获得精确匹配
我需要验证由“v”加正整数组成的版本号,仅此而已 例如“v4”,“v1004”
我有
import re
pattern = "\Av(?=\d+)\W"
m = re.match(pattern, "v303")
if m is None:
print "noMatch"
else:
print "match"
但这不起作用!删除 \A 和 \W 将匹配 v303,但也会匹配 v30G,例如
谢谢
I need to validate a version number consisting of 'v' plus positive int, and nothing else
eg "v4", "v1004"
I have
import re
pattern = "\Av(?=\d+)\W"
m = re.match(pattern, "v303")
if m is None:
print "noMatch"
else:
print "match"
But this doesn't work! Removing the \A and \W will match for v303 but will also match for v30G, for example
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
非常简单。首先,在您的模式上放置锚点:
现在,让我们将模式放在一起:
这样就可以了。
Pretty straightforward. First, put anchors on your pattern:
Now, let's put together the pattern:
That should do it.
我认为您可能需要
\b
(单词边界)而不是\A
(字符串开头)和\W
(非单词字符),您也不需要使用前瞻((?=...)
)。如果需要捕获 int,请尝试:
"\bv(\d+)"
,如果不需要,请尝试:"\bv\d+"
。编辑:您可能希望对 Python 正则表达式使用原始字符串语法,
r"\bv\d+\b"
,因为"\b"
是常规字符串中的退格字符。编辑 2:由于
+
是“贪婪”的,因此不需要或不需要尾随\b
。I think you may want
\b
(word boundary) rather than\A
(start of string) and\W
(non word character), also you don't need to use lookahead (the(?=...)
).Try:
"\bv(\d+)"
if you need to capture the int,"\bv\d+"
if you don't.Edit: You probably want to use raw string syntax for Python regexes,
r"\bv\d+\b"
, since"\b"
is a backspace character in a regular string.Edit 2: Since
+
is "greedy", no trailing\b
is necessary or desired.只需使用
Or 将其括起来
^\bv\d+\b$
即可完全匹配它。
Simply use
Or enclosed it with
^\bv\d+\b$
to match it entirely..