1

我正在做一个搜索功能,我想突出显示匹配的模式。所以,无论哪种情况,我都必须分别在字符串中添加和附加所有<$>模式</$>

highlight("RajkumarrAjkumarRAjkumaraj", "Ra") 
# should return "<$>Ra</$>jkumar<$>rA</$>jkumar<$>RA</$>jkuma<$>ra</$>j"

highlight("RajkumarrAjkumarRAjkumaraj", "ra") 
# should return "<$>Ra</$>jkumar<$>rA</$>jkumar<$>RA</$>jkuma<$>ra</$>j"

highlight("RajkumarrAjkumarRAjkumaraj", "rA") 
# should return "<$>Ra</$>jkumar<$>rA</$>jkumar<$>RA</$>jkuma<$>ra</$>j"

highlight("RajkumarrAjkumarRAjkumaraj", "RA") 
# should return "<$>Ra</$>jkumar<$>rA</$>jkumar<$>RA</$>jkuma<$>ra</$>j"
4

2 回答 2

3

你可以使用String#gsub().

def highlight(str, pattern)

    str.gsub(/(#{Regexp.escape(pattern)})/i, "<$>$1</$>")

end
于 2012-10-04T09:25:00.763 回答
1

试试这个

> "RajkumarrAjkumarRAjkumaraj".gsub(/(ra)/i, '<$>\1</$>')
于 2012-10-04T11:17:29.283 回答