Solved

Ruby RegEx search and replace

Posted on 2008-10-10
3
1,600 Views
Last Modified: 2013-11-13
This should be simple:

text = 'adam|paul|mike'

I want to replace that with   ->   <b>adam</b><b>paul</b><b>mike</b>

So each name seperated by a |  OR a name at the end of the string should be enclosed in <b> tags.  Here's what I have so far:

text.gsub(/[a-z]*[|\Z]/, '<b>\0</b>')

But this leaves off the last name.  I'd also like to replace [a-z]*  with just  .*  - (which for some reason is way off)

As a bonus, is there a way to also get the values inside the <b> tags to drop the  |    -  but that can always easily be done in a second step

Thanks!
0
Comment
Question by:ARACK04
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 60

Accepted Solution

by:
Geert Bormans earned 500 total points
ID: 22692963
use split to break the string in an array, change the diffrent items in place using collect and join the remainder array

text = 'adam|paul|mike'
arr = text.split('|')
arr.collect!{|a| '<b>' + a + '</b>' }
puts arr.join

easy, no?
0
 
LVL 60

Expert Comment

by:Geert Bormans
ID: 22692981
of course you can do this in one line
puts text.split('|').collect!{|a| '<b>' + a + '</b>' }.join
0
 

Author Closing Comment

by:ARACK04
ID: 31505258
Not sure why I assumed I needed a regex here.  Thanks!.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
301 redirect rails app 10 620
require 'icalendar' causes error 1 486
What does << do and mean in Ruby 2 487
RVM change location 4 280
Article by: narshlob
If you've ever programmed in Ruby and have come across either a proc or a lambda, you might have been wondering what the difference is between the two and when you would use one over the other. This article will try to explain the difference between…
In Ruby, Call or invoke a API DLL library is easily via Win32API class, win32-api gem or other gems. For general DLL API call, there are quite a few references, some good tips list below: http://www.rubytips.org/2008/05/13/accessing-windows-api-fro…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

710 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question