From: Wes Oldenbeuving Date: 2007-12-30T22:34:23+09:00 Subject: Re: replace words to be bold for each search word --------------enigA15A6AAA3337C49C863E2521 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Mark Toth wrote: > I have two strings: >=20 > The first string with dynamic content: > @string =3D "this is the example of the text" >=20 > The second one includes search words: > @search =3D "example text" >=20 > How can I do that it prints the search words with bold? >=20 > Result: > this is the example of the example Hi, You can use String#gsub to find and replace the words you want. The example you have given could be solved by the following script: ### Start code def highlight(text,search_string) keywords =3D search_string.squeeze.strip.split(" ").compact.uniq matcher =3D Regexp.new( '(' + keywords.join("|") + ')' ) highlighted =3D text.gsub(matcher) { |match| "#{match}" } return highlighted end text =3D "This is an example of the text." search =3D "example text" puts highlight(text,search) # =3D> This is an example of the text. ### End code There are probably plenty of opportunities to optimize and add defensive coding, such as stripping out regexp-meaningful characters from the search string, but this should be a start. Cheers, Wes 'Narnach' Oldenbeuving --------------enigA15A6AAA3337C49C863E2521 Content-Type: application/pgp-signature; name="signature.asc" Content-Description: OpenPGP digital signature Content-Disposition: attachment; filename="signature.asc" -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.7 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFHd55f2qpBjwxOjJIRApXUAJ9n32p60P1TLb4msZx8ayOtoed57gCeNH44 rXGDzEgy9u1HBZSBUuXlm6M= =rCAH -----END PGP SIGNATURE----- --------------enigA15A6AAA3337C49C863E2521--