简体   繁体   中英

Insert markers to a string matching a pattern irrespective of case in ruby

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM