python regex适用于在线测试,但不适用于程序

时间:2014-02-22 16:06:17

标签: python regex python-3.x

我试过了两次

color_regex_test1 = re.compile('[#]\w{3,6}')
print(color_regex_test1.match('color: #333;'))

color_regex_test2 = re.compile('([#]\w{3,6})')
print(color_regex_test2.match('color: #333;'))

并没有像我预期的那样工作......他们都打印无。 https://pythex.org/意味着它应该起作用

1 个答案:

答案 0 :(得分:7)

使用search代替matchmatch仅匹配字符串开头的模式。

>>> color_regex_test1.search('color: #333;').group()
'#333'

BTW,#在正则表达式中没有特殊含义。您无需将其放在[...]内以便按字面匹配:

>>> color_regex_test1 = re.compile('#\w{3,6}')
>>> color_regex_test1.search('color: #333;').group()
'#333'