Python 正则表达式:仅精确匹配 [英] Python regular expression: exact match only

查看:52
本文介绍了Python 正则表达式:仅精确匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题,但我找不到答案.

I have a very simple question, but I can't find an answer for this.

我有一些字符串,例如:

I have some string like:

test-123

我想要一些 smart 正则表达式来验证这个字符串是否与我的条件完全匹配.

I want to have some smart regular expression for validation if this string exact match my condition.

我希望有一个像这样的字符串:

I expect to have a strings like:

test-<number>

数字应该包含数字上从 1 到 * 的元素.

Where number should contains from 1 to * elements on numbers.

我正在尝试做这样的事情:

I'm trying to do something like this:

import re
correct_string = 'test-251'
wrong_string = 'test-123x'
regex = re.compile(r'test-\d+')
if regex.match(correct_string):
    print 'Matching correct string.'
if regex.match(wrong_string):
    print 'Matching wrong_string.'

所以,我可以看到两条消息(匹配正确和错误的字符串),但我真的希望只匹配正确的字符串.

So, I can see both messages (with matching correct and wrong string), but I really expect to match only correct string.

另外,我试图使用 search 方法而不是 match 但没有运气.

Also, I was trying to use search method instead of match but with no luck.

想法?

推荐答案

尝试在正则表达式中指定开始和结束规则:

Try with specifying the start and end rules in your regex:

re.compile(r'^test-\d+$')

这篇关于Python 正则表达式:仅精确匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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