Hay*_*ers 4 python regex python-3.x
我试过了两个
color_regex_test1 = re.compile('[#]\w{3,6}')
print(color_regex_test1.match('color: #333;'))
Run Code Online (Sandbox Code Playgroud)
和
color_regex_test2 = re.compile('([#]\w{3,6})')
print(color_regex_test2.match('color: #333;'))
Run Code Online (Sandbox Code Playgroud)
并且都没有像我预期的那样工作..他们都打印无. https://pythex.org/暗示它应该有效
用search而不是match.match仅匹配字符串开头的模式.
>>> color_regex_test1.search('color: #333;').group()
'#333'
Run Code Online (Sandbox Code Playgroud)
BTW,#在正则表达式中没有特殊含义.您不需要将其放入内部[...]以便按字面匹配:
>>> color_regex_test1 = re.compile('#\w{3,6}')
>>> color_regex_test1.search('color: #333;').group()
'#333'
Run Code Online (Sandbox Code Playgroud)