我需要验证下一个字符串的格式:
text-text-id-text
分隔符为“-”。第三列必须始终为ID。我编写了下面的正则表达式(在Python中),用于验证字符串:
分隔符为“-”,第三个字段必须是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匹配,但我对为什么第一个正则表达式如上所述有效很感兴趣。
(?=-|$)
,以确保第三列不是类似于“idiom”的内容。 - Tim Pietzcker