Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Ruby RegEx search and replace

Posted on 2008-10-10
3
Medium Priority
?
1,629 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 2000 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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

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

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…
This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Loops Section Overview
Suggested Courses
Course of the Month10 days, 2 hours left to enroll

927 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