我试过了两次
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/意味着它应该起作用
答案 0 :(得分:7)
使用search
代替match
。 match
仅匹配字符串开头的模式。
>>> 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'