gpt4 book ai didi

ruby - 如何将两个单词之间的信息 block 保存到文件中?

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:59 25 4
gpt4 key购买 nike

我有以下文件:

旧文件

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

文件2

new_file
Another text.
end

如何获取关键字“new_file”和“end”之间的信息并将其写入文件?

最佳答案

如果您的文件不是那么大,您可以将它们作为字符串读入(使用 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+ 尽可能少的任何字符(包括 a newline 作为 /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发生时关闭。

关于ruby - 如何将两个单词之间的信息 block 保存到文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37520927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com