我从文本中替换start#character word replace

时间:2014-10-08 13:53:54

标签: ruby-on-rails ruby ruby-on-rails-4

我从文本中替换start#character word replace。我的目标是从主题标签文本创建可点击链接

我用过.gsub()。但不行。

示例:

s = "#tag ddd#tagddd #taghh #tag aaaaa #####tag b###tag" str = "#tag" s.gsub(/\b"#{str}"\b/), "replaced")

我希望输出“替换ddd#tagddd #taghh替换aaaaa ####替换b ##替换”

谢谢

2 个答案:

答案 0 :(得分:0)

s = "#tag ddd#tagddd #taghh #tag aaaaa #####tag b###tag "
str = "#tag "

s.gsub(str, "replaced ")
#=> "replaced ddd#tagddd #taghh replaced aaaaa ####replaced b##replaced "

答案 1 :(得分:0)

我不确定这是你在找什么,但也许它会帮助你:

regexp = /#+\w+/
s = "#tag ddd#tagddd #taghh #tag aaaaa #####tag b###tag"
s.gsub(regexp, 'replaced')

我的控制台输出:

1.9.3p489 :001 > regexp = /#+\w+/
 => /#+\w+/ 
1.9.3p489 :002 > s = "#tag ddd#tagddd #taghh #tag aaaaa #####tag b###tag"
 => "#tag ddd#tagddd #taghh #tag aaaaa #####tag b###tag" 
1.9.3p489 :003 > s.gsub(regexp, 'replaced')
 => "replaced dddreplaced replaced replaced aaaaa replaced breplaced"

用于查看此正则表达式的rubular链接: http://rubular.com/r/y6eCNNp4i0