我有以下文件:
old_file
new_file
Some string.
end
Text in the middle that is not supposed to go to any of files.
new_file
Another text.
end
如何使用正则表达式创建具有以下内容的两个文件:
文件1
new_file
Some string.
end
file2的
new_file
Another text.
end
如何获取关键字“ new_file ”和“结束”之间的信息以将其写入文件?
答案 0 :(得分:2)
如果您的文件不是那么大,可以用字符串形式读取它们(使用File.read(file_name)
),然后运行以下正则表达式:
file_contents.scan(/^new_file$.*?^end$/m).select { |block| WRITE_TO_FILE_CODE_HERE }
请参阅regex demo
^new_file$.*?^end$
正则表达式匹配new_file
这是一个整行内容,然后0 +尽可能少的任何字符(包括使用新行作为/m
修饰符),然后end
(整行)。
否则,您可以将this answer here改为
printing = false
File.open(my_file).each_line do |line|
printing = true if line =~ /^new_file$/
puts line if printing
printing = false if line =~ /^end$/
end
找到起始行时打开文件,写入上面示例中puts line
的位置,并在printing false
出现时关闭。
答案 1 :(得分:1)
您还可以通过更改ruby中“line”的内容来读取chunk中的文件块:
File.open("file1.txt", "w") do |file1|
File.open("file2.txt", "w") do |file2|
enum = IO.foreach("old_file.txt", sep="\n\n")
file1.puts enum.next.strip
enum.next #discard
file2.puts enum.next.strip
end #automatically closes file2
end #automatically closes file1
通过将分隔符指定为“\ n \ n”,ruby将读取所有字符,包括两个连续的换行符,并将其作为“行”返回。
答案 2 :(得分:0)
如果修复了这种格式,那么您可以试试这个(new_file\n.*\nend)