替换字符串中包含数字的单词

时间:2014-11-05 11:25:54

标签: ruby-on-rails ruby

t = "Text with numbers such as 58, 22nd, 53m2, number9 and foo44bar"

我想把<span>放在这样的数字上:

t.gsub(/(\d+)([[:alnum:]]+)/,"<span>\\1\\2</span>") =>
"Text with numbers such as <span>58</span>, <span>22nd</span>, <span>53m2</span>, number9 and foo<span>44bar</span>"

我仍然遇到的唯一问题是当这个词不是以number9 and "foo<span>44bar</span>之类的数字开头时,我也试过了

t.gsub(/([[:alnum:]]+)(\d+)([[:alnum:]]+)/,"<span>\\1\\2\\3</span>")

但这也不太正确。

我确信我只是没有看到一些细节,一些帮助将不胜感激:)

1 个答案:

答案 0 :(得分:1)

试试这个:

t.gsub(/([[:alnum:]]*(\d+)[[:alnum:]]*)/, "<span>\\1</span>")