[英]Can not figure out where to put the '\n' in my code in order for regex to print line by line.
So I have been at this for a while now trying to figure out where to put the '\\n' in order for the output being set into a text document to be placed line by line. 因此,我已经花了一段时间了,试图弄清楚在何处放置“ \\ n”,以便将输出设置到文本文档中以逐行放置。 It is grouping the output into one big mess.
它将输出分组为一团糟。 I wanted for each line that matches my regex, to be saved on a seperate line.
我希望将与我的正则表达式匹配的每一行保存在单独的行中。
Code: 码:
import re
dns = []
with open('ns.txt', 'r') as file:
lines = file.read().splitlines()
for line in lines:
if re.search(r'^(add lb vserver )(\S+) (\S+) (\S+)(.+)$', "line"):
dns.append(line)
print(dns)
with open('dnsout.txt', 'w') as f:
f.writelines(lines)
dns.append(line)
必须是dns.append(line+"\\n")
。
updated (sorry for typo's) 更新 (对错打错了)
Since you're reading in all the lines into an array anyway. 因为无论如何您都将所有行读入数组。
Just read the entire file into a string. 只需将整个文件读入字符串即可。
Then clean it up with a find (?m)$(?:\\s*\\r?\\n)+
replace \\r\\n
然后使用查找
(?m)$(?:\\s*\\r?\\n)+
替换\\r\\n
清理
Use whatever CRLF translation your system uses. 使用系统使用的任何CRLF转换。
This just removes all extra linebreaks. 这只会删除所有多余的换行符。
If you want to make it with an extra line separation, make the replacement \\r\\n\\r\\n
. 如果要使用额外的行分隔符,请替换
\\r\\n\\r\\n
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.