在 python regex 中使用锚点来获得精确匹配 [英] Using anchors in python regex to get exact match

查看:28
本文介绍了在 python regex 中使用锚点来获得精确匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证由v"加上正整数组成的版本号,仅此而已例如v4"、v1004"

I need to validate a version number consisting of 'v' plus positive int, and nothing else eg "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,例如

But this doesn't work! Removing the \A and \W will match for v303 but will also match for v30G, for example

谢谢

推荐答案

非常简单.首先,在你的模式上放置锚点:

Pretty straightforward. First, put anchors on your pattern:

"^patternhere$"

现在,让我们把模式放在一起:

Now, let's put together the pattern:

"^v\d+$"

应该可以.

这篇关于在 python regex 中使用锚点来获得精确匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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