反向引用中的Ruby regex gsub更改

时间:2018-03-11 19:07:05

标签: ruby regex

我正在尝试使用以下内容查找并修改数组中的每个标记:

re = /(?<img><img .*? \/>)/
my_string.gsub re, '\k<img>'

Thi成功匹配所有图片代码,我可以在反向引用之前和之后添加内容,但是在那里添加内容? (即当我想向标签添加属性时?)

谢谢。

2 个答案:

答案 0 :(得分:2)

您可以使用这样的捕获组:

my_string = "<img src=\"\" />"
re = /(<img .*?)\s*(\/>)/
puts my_string.gsub re, '\1 more="here"\2'

请参阅online Ruby demo

<强>详情

  • (<img .*?) - 第1组后来称为\1img,空格和任何0+字符,尽可能少
  • \s* - 0+ whitespaces
  • (\/>) - 第2组(\2):/>子字符串。

答案 1 :(得分:0)

您可以在<img>标记内添加匹配组,然后以这种方式提取属性,然后对此进行处理。 不确定您是否可以使用gsub,但match非常强大,您可以阅读here。如果对字符串使用匹配,它将返回一个MatchData类对象,您可以使用[]方法访问其元素。此对象的元素是所有匹配,在下面的示例中,它们是整个字符串和所有属性。

回到你的问题,here是关于regex101的一个例子,你可以在其中看到如何匹配你正在寻找的每个特定属性。

最终结果如下:

re = /<img( src=\".*?\")?( alt=\".*?\")?( height=\".*?\")?( width=\".*?\")?(\/|\ \/)?>/

test = '<img src="smiley.gif" alt="Smiley face" height="42" width="42">'

matches = test.match(re)

matches
# => #<MatchData "<img src=\"smiley.gif\" alt=\"Smiley face\" height=\"42\" width=\"42\">" 1:" src=\"smiley.gif\"" 2:" alt=\"Smiley face\"" 3:" height=\"42\"" 4:" width=\"42\"" 5:nil>
matches[0]
# => "<img src=\"smiley.gif\" alt=\"Smiley face\" height=\"42\" width=\"42\">"
matches[1]
# => " src=\"smiley.gif\""
matches[2]
# => " alt=\"Smiley face\""
# ...