python - 一个简单的正则匹配问题
阿神
阿神 2017-04-18 10:20:43
0
3
728
In [33]: re.match('ab\\*c','ab*cd')
Out[33]: <_sre.SRE_Match object; span=(0, 4), match='ab*c'>

如上,没想明白为什么能匹配到,我的匹配模式中不是使用'\'将''转义成了字符串了吗,为什么最后还能匹配到结果??谢谢!!

阿神
阿神

闭关修行中......

reply all(3)
左手右手慢动作

Regular expressions use the backslash character ('') to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python's usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\' as the pattern string, because the regular expression must be , and each backslash must be expressed as inside a regular Python string literal.

In fact, I don’t understand which pattern you want to match, but your problem should be solved by the above.
It is recommended to use raw string.

Peter_Zhu
'ab\*c'

This rule is indeed compile after

'ab*c' // 这里*表示匹配`*`这个字符

Then of course it can match the target string ab*cd 中的 ab*c

黄舟

Add an r if you don’t want it to match.

re.match(r'ab\*c','ab*cd')
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template