Python转义正则表达式特殊字符 [英] Python escape regex special characters

查看:354
本文介绍了Python转义正则表达式特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python是否具有可用于转义正则表达式中的特殊字符的功能?

Does Python have a function that I can use to escape special characters in a regular expression?

例如,我被卡住:\ 应该成为我不会\卡住\:\\

推荐答案

使用re.escape

Use re.escape

re.escape(string)
>>> re.escape('\ a.*$')
'\\\\\\ a\\.\\*\\$'
>>> print(re.escape('\ a.*$'))
\\\ a\.\*\$
>>> re.escape('www.stackoverflow.com')
'www\\.stackoverflow\\.com'
>>> print(re.escape('www.stackoverflow.com'))
www\.stackoverflow\.com

请参阅: http://docs.python.org/ library / re.html#module-contents

在此重复:


re.escape(string)

re.escape(string)

返回所有非字母数字的字符串,反斜杠;如果你想匹配一个可能具有正则表达式元字符的任意文字字符串,这是非常有用的。

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

这篇关于Python转义正则表达式特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆