[英]Ruby regex to capture part of content between two strings
With ruby gsub()
, in string <code>balabala or blank \n another balabala or blank</code>
, replacing all \n
inside <code>...</code>
block into <br>
, but do nothing to the content outside <code>...</code>
.使用 ruby
gsub()
,在字符串<code>balabala or blank \n another balabala or blank</code>
中,将<code>...</code>
块中的所有\n
替换为<br>
,但不执行任何操作<code>...</code>
之外的内容。
I tried /<code>.*(\\n?).*<\/code>/
but not working:我试过
/<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>
Match all substrings between <code>
and </code>
and replace all \n
with <br>
in those matches only:匹配
<code>
和</code>
之间的所有子字符串,并仅在这些匹配项中将所有\n
替换为<br>
:
html = html.gsub(/<code>.*?<\/code>/m) { $~[0].gsub('\n', '<br>') }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.