Python3基础-正则表达式转义注意事项python中对元字符的转义使⽤双反斜杠 \\ 来表⽰
# 普通元字符的转义
# 不转义
print(re.findall('$', '!@#$%^&'))
#>>> ['']
# 双反斜杠转义
print(re.findall('\\$','!@#$%^&'))
#>>> ['$']
# 单反斜杠转义
print(re.findall('\$', '!@#$%^&'))
使⽤⼀个反斜杠 \ 也可以达到转义的效果,那为什么还要写两个呢?
s = 'i\'m superman'  #python本⾝使⽤ \ 来转义⼀些特殊字符
print(s)  #输出 i'm superman
#print('\')  #报错  SyntaxError: EOL while scanning string literal  因为\把后⾯的引号给转义了
print('\\')  #输出的是 \
#原⽣字符串
print(r'\\')  # 输出的是 \\
字符串转义
eg \n 换⾏
print('Hello \W world \npython')
"""
执⾏结果为
Hello \W world
python
备注:“\n”已转义为换⾏符,⽽“\W”没有发⽣转义,原因是“\W”在“字符串转义”中并不对应着特殊字符,没有特殊含义。
"""
原封不动输出为“Hello\World\nPython”
#⽅法1 \\
print('Hello \W world \\npython')
#⽅法2 r
print(r'Hello \W world \npython')
"""
执⾏结果
Hello \W world \npython
Hello \W world \npython
"""
正则转义
import re
string = '3\8'
python正则表达式判断m = re.search('(\d+)\\\\', string)
if m is not None:
up(1))  # 结果为:3    \\\\  字符转义成\\  再正则转义为\
n = re.search(r'(\d+)\\', string)
if n is not None:
up(1)) #结果为3    r \\  字符转义还是\\  再正则转义为\
#正则表达式字符串需要经过两次转义,这两次分别是上⾯的“字符串转义”和“正则转义”