如何将一个或多个换行符更改为ruby中的某些内容?

时间:2021-06-22 21:11:17

How can I change one or more line breaks to something in ruby?

如何将一个或多个换行符更改为ruby中的某些内容?

article.content.gsub(/\n/, "<br />")

above code will change every 1 line break to <br /> tag, however, I want to change one or more \n to <br /> tag. In that way, continuous line breaks with empty lines will be substitued into a single <br /> tag. How can I do that?

上面的代码会将每1行中断更改为
标记,但是,我想将一个或多个\ n更改为
标记。这样,带有空行的连续换行将被替换为单个
标签。我怎样才能做到这一点?

2 个解决方案

#1


2  

Are you looking for this?

你在找这个吗?

article.content.gsub(/\n+/, "<br />")

Note the plus sign after the \n. That will change any sequence of one or more newlines to a single <br>.

注意\ n后面的加号。这会将一个或多个换行符的任何序列更改为单个

#2


1  

It also might be helpful to quickly test Ruby regular expressions against sample data using Rubular.

使用Rubular快速测试Ruby正则表达式对样本数据也可能有所帮助。

#1


2  

Are you looking for this?

你在找这个吗?

article.content.gsub(/\n+/, "<br />")

Note the plus sign after the \n. That will change any sequence of one or more newlines to a single <br>.

注意\ n后面的加号。这会将一个或多个换行符的任何序列更改为单个

#2


1  

It also might be helpful to quickly test Ruby regular expressions against sample data using Rubular.

使用Rubular快速测试Ruby正则表达式对样本数据也可能有所帮助。