Bri*_*ong 6 ruby regex ruby-on-rails
我有一些带有强硬换行符的文字,如下所示:
This should all be on one line
since it's one sentence.
This is a new paragraph that
should be separate.
Run Code Online (Sandbox Code Playgroud)
我想删除单个换行符,但保留双换行符,如下所示:
This should all be on one line since it's one sentence.
This is a new paragraph that should be separate.
Run Code Online (Sandbox Code Playgroud)
有没有一个正则表达式来做到这一点?(或一些简单的方法)
到目前为止,这是我唯一有效的解决方案,但却感觉很自负.
txt = txt.gsub(/(\r\n|\n|\r)/,'[[[NEWLINE]]]')
txt = txt.gsub('[[[NEWLINE]]][[[NEWLINE]]]', "\n\n")
txt = txt.gsub('[[[NEWLINE]]]', " ")
Run Code Online (Sandbox Code Playgroud)
Phr*_*ogz 10
替换所有未在换行符之后或之前的换行符:
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. "
Run Code Online (Sandbox Code Playgroud)
或者,对于没有外观的Ruby 1.8:
txt.gsub! /([^\n])\n([^\n])/, '\1 \2'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7415 次 |
| 最近记录: |