Python正则表达式:仅与完全匹配

时间:2017-07-21 18:50:48

标签: python regex

我有一个非常简单的问题,但我无法找到答案。

我有一些字符串:

test-123

如果此字符串与我的条件完全匹配,我想要一些smart正则表达式进行验证。

我希望有一个像:

这样的字符串
test-<number>

其中数字应包含数字上的1到*元素。

我试图做这样的事情:

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.'

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

此外,我尝试使用search方法代替match,但没有运气。

想法?

6 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:1)

从Python 3.4开始,您可以使用re.fullmatch避免将^$添加到您的模式中。

>>> import re
>>> p = re.compile(r'\d{3}')
>>> bool(p.match('1234'))
True

>>> bool(p.fullmatch('1234'))
False

答案 2 :(得分:0)

\btest-\d+\b之类的模式可以帮到你;

matches = re.search(r'\btest-\d+\', search_string)

Demo

这需要匹配字边界,因此可以防止在您想要的匹配后出现其他子字符串。

答案 3 :(得分:0)

您可以尝试re.findall()

import re
correct_string = 'test-251'

if len(re.findall("test-\d+", correct_string)) > 0:
    print "Match found"

答案 4 :(得分:0)

我认为这可能对您有帮助-

import re
pattern = r"test-[0-9]+$"
s = input()

if re.match(pattern,s) :
    print('matched')
else :
    print('not matched')

答案 5 :(得分:0)

对于完全匹配regex = r'^ (some-regex-here) $'

^:字符串的开头

$:字符串结尾