Solved

Ruby RegEx search and replace

Posted on 2008-10-10
3
1,576 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
  • 2
3 Comments
 
LVL 60

Accepted Solution

by:
Geert Bormans earned 500 total points
Comment Utility
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
Comment Utility
of course you can do this in one line
puts text.split('|').collect!{|a| '<b>' + a + '</b>' }.join
0
 

Author Closing Comment

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

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

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…
Recently I spent hours debugging an issue in a Rails project where ActiveRecord was causing MySQL errors trying to create a User object of a class at the top level of a Single Table Inheritance model structure.  It turns out `.create` behaves differ…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

762 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now