Ruby on rails 如果前两个字母与模式匹配,如何修改字符串?
我有这样的字符串:Ruby on rails 如果前两个字母与模式匹配,如何修改字符串?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有这样的字符串: $5.00 off blah blah 5% off blah blah This off should not match 我希望匹配以^([$]?[\d.]+[%]?)off开头的字符串。* 并将其转换为: <strong>$5.00 off</strong> blah blah <strong>5% off</strong> blah blah This off should not match 这应该可以做到: st
$5.00 off blah blah
5% off blah blah
This off should not match
我希望匹配以^([$]?[\d.]+[%]?)off开头的字符串。*
并将其转换为:
<strong>$5.00 off</strong> blah blah
<strong>5% off</strong> blah blah
This off should not match
这应该可以做到:
string.gsub(/^([$]?[\d.]+[%]?) off .*/, "<strong> \\0 </strong>" )
string.gsub(/^([$]?[\d.]+[%]?)关闭。*/,“\\0”)
\\O
指的是匹配的字符串。基于一个标题的答案,修改为您想要的:
string.gsub(/^([$]?[\d.]+[%]? off)( .*)$/, '<strong>\1</strong>\2' )
string.gsub(/^([$]?[\d.]+[%]?off)(.*)$/,“\1\2”)
将整个字符串放入标记中。有没有一种方法可以像问题中那样在strong中只打“5美元折扣”呢?谢谢你的指导。我沿着这条路走到了.gsub(/^([$]?[\d.]+[%]?off)(.*)/,“\\1“+'\\2”)
这太奇怪了:“$Nice weekend!”。gsub(/^\$,“bold”+“\\0”+“bold”)=>“bold$bold$bold Nice weekend!”
啊,你说得对。这是答案中的*
。现在删除与\\0
一起使用的。
string.gsub(/^([$]?[\d.]+[%]? off)( .*)$/, '<strong>\1</strong>\2' )