使用gsub替换/剥离空行

时间:2022-07-22 16:53:55

I have an HTML page:

我有一个HTML页面:

    <strong>

    Product Name:




</strong>

I want to strip its empty lines (^\n or ^$). Expected HTML is:

我想剥去它的空行(^ \ n或^ $)。预期的HTML是:

    <strong>
    Product Name:
</strong>

Here is my syntax:

这是我的语法:

r.gsub!(/^\\n/, '')

It doesn't seem to work. I tried many combinations and I can't get it to do anything. puts r.class => string and r always have spaces in them. I'm actually trying a larger set of reductions:

它似乎不起作用。我尝试了很多组合,我无法做任何事情。 puts r.class => string和r总是有空格。我实际上正在尝试更大的减少量:

r.gsub!(/\\n\s+?/, '').gsub!(/\\t\s+?/, '').gsub!(/^\\n/, '')

2 个解决方案

#1


2  

The problem seems to be that you are escaping backslashes when you shouldn't be. E.g. /\\n/ will match the string \n, not a newline character. /\n/ will match a newline character. Same goes for \t.

问题似乎是你不应该逃避反斜杠。例如。 / \\ n /将匹配字符串\ n,而不是换行符。 / \ n /将匹配换行符。同样适用于\ t。

If you want to play around with Ruby regular expressions, I recommend checking out Rubular.

如果你想玩Ruby正则表达式,我建议你查看Rubular。

Also, be careful with gsub!, especially chaining them like that. gsub! returns nil if nothing is replaced and you will get an undefined method for nil error on subsequent calls. You're much better off with

另外,小心gsub!,特别是那样链接它们。 GSUB!如果没有替换任何内容,则返回nil,并且在后续调用中将获得未定义的nil错误方法。你好多了

r = r.gsub(...).gsub(...) ...

#2


1  

I got it to work.

我得到了它的工作。

r = r.gsub(/\t\s+?/, "")
r = r.gsub(/^\s*$/, "")

The "\n" can be encapsulated by \s*. $ does not mean \n.

“\ n”可以用\ s *封装。 $并不代表\ n。

#1


2  

The problem seems to be that you are escaping backslashes when you shouldn't be. E.g. /\\n/ will match the string \n, not a newline character. /\n/ will match a newline character. Same goes for \t.

问题似乎是你不应该逃避反斜杠。例如。 / \\ n /将匹配字符串\ n,而不是换行符。 / \ n /将匹配换行符。同样适用于\ t。

If you want to play around with Ruby regular expressions, I recommend checking out Rubular.

如果你想玩Ruby正则表达式,我建议你查看Rubular。

Also, be careful with gsub!, especially chaining them like that. gsub! returns nil if nothing is replaced and you will get an undefined method for nil error on subsequent calls. You're much better off with

另外,小心gsub!,特别是那样链接它们。 GSUB!如果没有替换任何内容,则返回nil,并且在后续调用中将获得未定义的nil错误方法。你好多了

r = r.gsub(...).gsub(...) ...

#2


1  

I got it to work.

我得到了它的工作。

r = r.gsub(/\t\s+?/, "")
r = r.gsub(/^\s*$/, "")

The "\n" can be encapsulated by \s*. $ does not mean \n.

“\ n”可以用\ s *封装。 $并不代表\ n。