用法:
re.escape(pattern)转义
pattern中的特殊字符。如果您想匹配其中可能包含正则表达式元字符的任意文字字符串,这很有用。例如:>>> print(re.escape('https://www.python.org')) https://www\.python\.org >>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:" >>> print('[%s]+' % re.escape(legal_chars)) [abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&'\*\+\-\.\^_`\|\~:]+ >>> operators = ['+', '-', '*', '/', '**'] >>> print('|'.join(map(re.escape, sorted(operators, reverse=True)))) /|\-|\+|\*\*|\*此函数不能用于
sub()和subn()中的替换字符串,只能转义反斜杠。例如:>>> digits_re = r'\d+' >>> sample = '/usr/sbin/sendmail - 0 errors, 12 warnings' >>> print(re.sub(digits_re, digits_re.replace('\\', r'\\'), sample)) /usr/sbin/sendmail - \d+ errors, \d+ warnings在 3.3 版中更改:
'_'字符不再转义。在 3.7 版中更改:只有在正则表达式中具有特殊含义的字符才会被转义。因此,
'!','"','%',"'",',','/',':',';','<','=','>','@', 和"`"不再逃脱。
相关用法
- Python re.compile用法及代码示例
- Python re.fullmatch()用法及代码示例
- Python re.split用法及代码示例
- Python re.Match.groupdict用法及代码示例
- Python re.Pattern.match用法及代码示例
- Python re.Pattern.search用法及代码示例
- Python re.Match.group用法及代码示例
- Python Regex re.MatchObject.groups()用法及代码示例
- Python re.Match.groups用法及代码示例
- Python Regex re.MatchObject.groupdict()用法及代码示例
- Python re.search() vs re.match()用法及代码示例
- Python re.sub用法及代码示例
- Python re.Match.start用法及代码示例
- Python re.Match.__getitem__用法及代码示例
- Python re.findall用法及代码示例
- Python re.Pattern.fullmatch用法及代码示例
- Python re.X用法及代码示例
- Python Numpy recarray.tostring()用法及代码示例
- Python reduce()用法及代码示例
- Python response.status_code用法及代码示例
注:本文由纯净天空筛选整理自python.org大神的英文原创作品 re.escape。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
