I am doing a search functionality where I want to highlight the matched pattern. SO, irrespective of the cases, I have to prepend and append all the patterns in the string with a <$>
and </$>
respectively.
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"
You could use String#gsub()
.
def highlight(str, pattern)
str.gsub(/(#{Regexp.escape(pattern)})/i, "<$>$1</$>")
end
尝试这个
> "RajkumarrAjkumarRAjkumaraj".gsub(/(ra)/i, '<$>\1</$>')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.