我试图区分Linux/Unix行尾字符\n
和Windows行尾{
import regex
winpattern = regex.compile("[(?m)[\r][\n]$",regex.DEBUG|regex.MULTILINE)
linuxpattern = regex.compile("^*.[^\r][\n]$", regex.DEBUG)
for i, line in enumerate(open('file8.py')):
for match in regex.finditer(linuxpattern, line):
print 'Found on line %s: %s' % (i+1, match.groups())
winpattern
和{linuxpattern
只匹配Linux下线,winpattern
只匹配Windows下线。有什么建议吗?在
当以文本文件的形式打开文件时,Python默认使用通用换行模式(请参见PEP 278),这意味着它将三个换行类型}全部转换为
\r\n
、\r
和{\n
。这意味着您的正则表达式是无关的:当您读取文件时,您已经丢失了有关换行符类型的信息。在要禁用换行符转换,应将} (对于python<;3,使用^{} ):
newline=''
参数传递给^{之后,这些正则表达式将起作用:
^{pr2}$注意,当使用
re.MULTILINE
时,$
匹配换行符之前的右,并且只匹配没有它的字符串结尾。要正确匹配任何换行符,只需删除$
。在如果要匹配完整行的正则表达式,请使用如下方法:
相关问题 更多 >
编程相关推荐