我发现有不同的方法来匹配 python 正则表达式中的新行。例如,下面代码中使用的所有模式都可以匹配新行
str = 'abc\n123'
pattern = '\n' # print outputs new line
pattern2 = '\\n' # print outputs \n
pattern3 = '\\\n' # print outputs \ and new line
pattern4 = r'\n' # print outputs \n
s = re.search(pattern, str).group()
print ('a' + s + 'a')
我对此有两个问题:
pattern 是换行符,pattern2 和pattern4 是\n。为什么 python 正则表达式为不同的字符串生成相同的模式?
不知道为什么pattern3也生成相同的模式。当传递给重新解析器时,pattern3 代表 \ + 新行,为什么重新解析器将其转换为仅匹配新行?
我正在使用Python 3
组合\n
表示“换行符”bothPython本身and in re
表达式以及 (https://docs.python.org/2.0/ref/strings.html).
在常规 Python 字符串中,\n
被翻译为换行符。换行符code然后被送入re
解析器作为文字字符。
A doublePython 字符串中的反斜杠被转换为单个反斜杠。因此,一个字符串"\\n"
内部存储为"\n"
,并且当发送到re
解析器,it反过来识别这个组合\n
表示换行代码。
The r
符号是避免输入双反斜杠的快捷方式:
在前缀为的字符串文字中,反斜杠不会以任何特殊方式处理'r'
(https://docs.python.org/2/library/re.html)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)