【发布时间】:2017-12-27 22:15:54
【问题描述】:
我有一个非常简单的问题,但我找不到答案。
我有一些类似的字符串:
test-123
如果这个字符串完全符合我的条件,我想要一些 smart 正则表达式进行验证。
我希望有这样的字符串:
test-<number>
其中 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,但没有运气。
想法?
【问题讨论】: