Python regexp works in an online test, but not a program

I tried both

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

and

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

and do not work as I expected. Both of them print None. https://pythex.org/ implies that it should work

+3
source share
1 answer

Use searchinstead match. matchmatches the pattern only at the beginning of the line.

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

BTW is #not particularly significant in regular expression. You do not need to put it inside [...]to fit it literally:

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

All Articles