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

时间:2021-07-21 09:58:16

I have 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 neither work as I expected.. they both print None. https://pythex.org/ implies that it should work

并且都没有像我预期的那样工作..他们都打印无。 https://pythex.org/暗示它应该有效

1 个解决方案

#1


7  

Use search instead of match. match matches the pattern only at the beginning of the string.

使用搜索而不是匹配。匹配仅匹配字符串开头的模式。

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

BTW, # has no special meaning in regular expression. You don't need to put it inside [...] to match it literally:

顺便说一下,#在正则表达式中没有特殊含义。你不需要把它放在[...]内以便按字面意思匹配它:

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

#1


7  

Use search instead of match. match matches the pattern only at the beginning of the string.

使用搜索而不是匹配。匹配仅匹配字符串开头的模式。

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

BTW, # has no special meaning in regular expression. You don't need to put it inside [...] to match it literally:

顺便说一下,#在正则表达式中没有特殊含义。你不需要把它放在[...]内以便按字面意思匹配它:

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