我必须在给定字符串内匹配此模式 [**],但它没有给出准确的结果。
import re
str1 = '[**] [1:123:43] hello madam [**]'
m1 = re.match('/[/*/*/] .*', str1)
请帮忙!!
最佳答案
使用反斜杠(\
)转义元字符,而不是正斜杠(/
):
>>> import re
>>> str1 = '[**] [1:123:43] hello madam [**]'
>>> m1 = re.match(r'\[\*\*\] .*', str1)
>>> m1
<_sre.SRE_Match object at 0x0000000002898100>
>>> m1.group()
'[**] [1:123:43] hello madam [**]'
顺便说一句,使用r'raw stringliteral'
,您不需要转义反斜杠本身。
如果您只想检查字符串是否以 [**]
开头,请使用 str.startswith
:
>>> str1.startswith('[**]')
True
关于python - Python 中的特殊字符模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21335135/