【问题标题】:Ruby regex to capture part of content between two stringsRuby正则表达式捕获两个字符串之间的部分内容
【发布时间】:2020-11-30 11:32:39
【问题描述】:

使用 ruby​​ gsub(),在字符串 <code>balabala or blank \n another balabala or blank</code> 中,将 <code>...</code> 块内的所有 \n 替换为 <br>,但对 <code>...</code> 之外的内容不做任何事情。

我尝试了/<code>.*(\\n?).*<\/code>/ 但没有工作:

html = '<pre>do \n nothing<code>line \n break</code></pre>'

html = html.gsub(/<code>.*(\\n?).*<\/code>/) { "<br>" }

print html

# actual result: <pre>do \n nothing<br></pre>

# expect result: <pre>do \n nothing<code>line <br> break</code></pre>

【问题讨论】:

    标签: regex ruby


    【解决方案1】:

    匹配&lt;code&gt;&lt;/code&gt; 之间的所有子字符串,并仅在这些匹配项中将所有\n 替换为&lt;br&gt;

    html = html.gsub(/<code>.*?<\/code>/m) { $~[0].gsub('\n', '<br>') }
    

    【讨论】:

      猜你喜欢
      • 2019-01-16
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      相关资源
      最近更新 更多