如何使正则表达式匹配整个字符串?

40
假设我有一个字符串,例如test-123。 我想测试它是否匹配类似于test-<数字>的模式,其中<数字>表示一个或多个数字符号。
我尝试了这段代码:
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.'

如何使只有correct_string与之匹配,而wrong_string不匹配?我尝试使用.search而不是.match但没有帮助。


相似问题:https://dev59.com/Im855IYBdhLWcg3wvXDd请仅返回翻译后的文本。 - Gangula
6个回答

60

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

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

我明白了,谢谢。在发布我的问题后,我发现了这个错误。 - smart
4
@smart 只需要加上 $ 符号,因为 re.match 会自动假设正则表达式的开头是 ^ - CDahn
@CDahn,我知道。谢谢! - smart
使用正则表达式多年,我从未知道“^”和“+$”是什么。更详细的解释在这里:https://dev59.com/A1sX5IYBdhLWcg3wDb6L - Dr4kk0nnys

26

精确匹配的正则表达式为 regex = r'^(在此处填写正则表达式)$'

^ : 字符串开始

$ : 字符串结束


26

自从Python 3.4版本以后,你可以使用re.fullmatch来避免在模式中添加^$

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

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

这是正确的方式,孩子! :) - D Left Adjoint to U

3

我认为这可能会对你有所帮助 -

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

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

2
您可以尝试使用re.findall()函数:
import re
correct_string = 'test-251'

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

0
一个像 \btest-\d+\b 这样的模式应该适合你;
matches = re.search(r'\btest-\d+\', search_string)

演示

这需要匹配单词边界,因此防止其他子字符串出现在您所需的匹配之后。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接