Ruby - 使用 gsub 在匹配的正则表达式的任一侧添加标签

Ruby - Add tag either side of matched regex with gsub

我这里有一个正则表达式:https://rubular.com/r/3p9WVitnlZQU3i

当 ping slack API 时,即使有多行,它也会将 blockquotes 转换为每行开头带有 > 的单独行。我想用块引号将它们包装起来:

以防万一 link 在将来某个时间点过期,这里是要匹配的测试字符串:

> This is a blockquote line
testing a new line
> 1- Another new blockquote section
> 2- And this is part of the same blockquote
> And this is the final line of this blockquote
testing another
> 1- Another new blockquote
> 2- And the final line of the 3rd blockquote

这是正则表达式

^>.*

正则表达式工作正常,我正在尝试使用 gsub 或其他方法将它们包装在块引号中,因此最终结果将是:

<blockquote>This is a blockquote line</blockquote>
testing a new line
<blockquote>1- Another new blockquote section
2- And this is part of the same blockquote
And this is the final line of this blockquote</blockquote>
testing another
<blockquote>1- Another new blockquote
2- And the final line of the 3rd blockquote</blockquote>

或者即使这非常困难,如果它只是将以 &gt; 开头的每一行都包裹在 blockquote 标记中,那也很好,因为我可以不添加底部边距,它们看起来像一个大报价。

老实说,我有点迷茫,但我想我正在尝试做这样的事情:

wrap_in_blockquote = replace_backticks2.gsub('^&gt;.*','<blockquote>/0</blockquote>')

但我不知道我是否需要单独遍历匹配项,或者这会这样做,或者我应该使用什么语法,因为我不熟悉 gsub 并且在文档中苦苦挣扎。任何帮助表示赞赏。

您可以使用

s = "&gt; This is a blockquote line\ntesting a new line\n&gt; 1- Another new blockquote section\n&gt; 2- And this is part of the same blockquote\n&gt; And this is the final line of this blockquote\ntesting another\n&gt; 1- Another new blockquote\n&gt; 2- And the final line of the 3rd blockquote"
rx = /^&gt;(.*)/
puts s.gsub(rx, '<blockquote></blockquote>')

参见Ruby online demo。输出:

<blockquote> This is a blockquote line</blockquote>
testing a new line
<blockquote> 1- Another new blockquote section</blockquote>
<blockquote> 2- And this is part of the same blockquote</blockquote>
<blockquote> And this is the final line of this blockquote</blockquote>
testing another
<blockquote> 1- Another new blockquote</blockquote>
<blockquote> 2- And the final line of the 3rd blockquote</blockquote>

详情:

^&gt;(.*) 匹配行首 ^,然后匹配 &gt;,然后 捕获 任何零个或多个到第 1 组使用 (.*) 尽可能多的换行字符以外的字符,其中括号创建 ID 为 1 的捕获组(因此, 用于替换模式以将组值放回到结果中字符串).

注意替换模式字符串文字中的单引号,如果使用双引号,则需要加倍反斜杠。

有时使用代码比使用非常复杂的正则表达式更容易。 它将更具可读性,之后如果您需要更改某些内容,您或您的同事将不胜感激。

text = DATA.read
block = "<blockquote>"
text.each_line do |line|
  if line[/^&gt;/]
      block << line.sub(/^&gt;/,"")
  else
      unless block=="<blockquote>"
        puts "#{block.chomp}</blockquote>" 
        block = "<blockquote>"
      end
      puts line
    end
end
puts block.chomp << "</blockquote>" unless block=="<blockquote>"

它给出了你所问的

<blockquote> This is a blockquote line</blockquote>
testing a new line
<blockquote> 1- Another new blockquote section
 2- And this is part of the same blockquote
 And this is the final line of this blockquote</blockquote>
testing another
<blockquote> 1- Another new blockquote
 2- And the final line of the 3rd blockquote</blockquote>

有关工作演示,请参阅 here