【发布时间】:2014-08-15 11:10:10
【问题描述】:
我必须验证下一个字符串格式:
text-text-id-text
分隔符是字符'-'。第三列必须始终是 id。我写了下一个验证字符串的正则表达式(在python中):
import re
s = 'col1-col2-col3-id' # any additional text at the end
# is allowed e.g. -col4-col5
print re.match('^(.*-){3}id(-.*)?$', s) # ok
print re.match('^(.*-){1}id(-.*)?$', s) # still ok, is should not be
我尝试添加非贪婪模式,但结果还是一样:
^(.*?-){1}id(-.*)?$
我的正则表达式中缺少什么?我可以像这样验证字符串:
>>> import re
>>> print re.split('-', 'col1-col2-col3-id')
['col1', 'col2', 'col3', 'id']
然后检查第三个元素是否匹配 id,但我感兴趣的是为什么第一个正则表达式会像上面提到的那样工作。
【问题讨论】: