gpt4 book ai didi

ruby-on-rails - 使用 Ruby 从文本中删除硬换行符

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

我有一些带有硬换行符的文本,如下所示:

This should all be on one line 
since it's one sentence.

This is a new paragraph that
should be separate.

我想删除单个换行符但保留双换行符,所以它看起来像这样:

This should all be on one line since it's one sentence.

This is a new paragraph that should be separate.

是否有一个正则表达式可以做到这一点? (或一些简单的方法)

到目前为止,这是我唯一可行但感觉很老套的解决方案。

txt = txt.gsub(/(\r\n|\n|\r)/,'[[[NEWLINE]]]')
txt = txt.gsub('[[[NEWLINE]]][[[NEWLINE]]]', "\n\n")
txt = txt.gsub('[[[NEWLINE]]]', " ")

最佳答案

替换所有后面没有或前面没有换行符的换行符:

text = <<END
This should all be on one line
since it's one sentence.

This is a new paragraph that
should be separate.
END

p text.gsub /(?<!\n)\n(?!\n)/, ' '
#=> "This should all be on one line since it's one sentence.\n\nThis is a new paragraph that should be separate. "

或者,对于没有 lookarounds 的 Ruby 1.8:

txt.gsub! /([^\n])\n([^\n])/, '\1 \2'

关于ruby-on-rails - 使用 Ruby 从文本中删除硬换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4833165/

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