简体   繁体   English

在python正则表达式中使用锚点来获得完全匹配

[英]Using anchors in python regex to get exact match

I need to validate a version number consisting of 'v' plus positive int, and nothing else eg "v4", "v1004" 我需要验证由'v'加上正整数组成的版本号,而不需要其他任何东西,例如“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 例如,删除\\ A和\\ W将匹配v303,但也将匹配v30G

Thanks 谢谢

Pretty straightforward. 非常直截了当。 First, put anchors on your pattern: 首先,在您的模式上放置锚点:

"^patternhere$"

Now, let's put together the pattern: 现在,让我们把模式放在一起:

"^v\d+$"

That should do it. 应该这样做。

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 (?=...) ). 我想你可能想要\\b (单词边界)而不是\\A (字符串的开头)和\\W (非单词字符),你也不需要使用lookahead( (?=...) )。

Try: "\\bv(\\d+)" if you need to capture the int, "\\bv\\d+" if you don't. 尝试: "\\bv(\\d+)"如果需要捕获int, "\\bv\\d+"如果不需要。

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. 编辑 :您可能希望使用Python正则表达式的原始字符串语法r"\\bv\\d+\\b" ,因为"\\b"是常规字符串中的退格符。

Edit 2 : Since + is "greedy", no trailing \\b is necessary or desired. 编辑2 :由于+是“贪婪”,因此不需要或不需要尾随\\b

Simply use 简单地使用

 \bv\d+\b

Or enclosed it with ^\\bv\\d+\\b$ 或用^\\bv\\d+\\b$括起来

to match it entirely.. 完全匹配..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM