假设我有一个类似 test-123
的字符串.
我想测试它是否匹配 test-<number>
这样的模式, 其中<number>
表示一个或多个数字符号。
我试过这段代码:
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
但它没有帮助。
最佳答案
尝试在正则表达式中指定开始和结束规则:
re.compile(r'^test-\d+$')
关于python - 如何使正则表达式匹配整个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45244813/