【问题标题】:Regular expression query/replacement - Ruby正则表达式查询/替换 - Ruby
【发布时间】:2016-03-24 00:55:30
【问题描述】:

我有一组 HTML,我希望在其中扫描“img src”的每个实例,并用一个变量替换“src”的值,在这个实例中是“cid:ii_151afcf74cab7d3b”。每个实例的“src”内容会有所不同。我将如何使用正则表达式来做到这一点?

<img src="cid:ii_1w1afcd4cab7d3b" alt="Inline image 1" width="517" height="291">

【问题讨论】:

  • html.gsub(/img src="[^"]*"/, "img src=\"#{var}\"")?

标签: html ruby-on-rails ruby regex


【解决方案1】:

表达式:

/(?&lt;=src=")([^"]+)/ 将匹配您的 src 内容而没有 " 符号

(?&lt;=src=") 是正向后视,会匹配但不考虑

([^"]+) 匹配除" 之外的任何内容,它将匹配您在src="will_match_whatever_except_double_quotes" 中输入的所有内容

Live

【讨论】:

    【解决方案2】:

    您可以像在字符串和符号中一样在正则表达式中进行插值:

    str = 'foo<img src="bar" alt="Inline image 1" width="517" height="291">'
    src = /<img src="#{src}" alt="Inline image 1" width="517" height="291">/
    
    str =~ src #=> 4
    

    编辑:我忘了,既然你要替换,你需要使用String#gsub/String#gsub!,或者如果你想做一些花哨的事情,也许String#scan

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      • 2012-10-21
      • 2010-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多