Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Ruby > Easy way to replace all non-alpha numeric chars in a string?

Reply
Thread Tools

Easy way to replace all non-alpha numeric chars in a string?

 
 
deja@homerlex.mailshell.com
Guest
Posts: n/a
 
      05-31-2006
Is there an easy (clean) method to replace all non-alpha numeric chars
in a string with and underscore?

for example:

I want to transform the following string:

"The book titled 'Ruby is Great' was written on 05/31/2006"

into:

"The_book_titled__Ruby is Great__was written on 05_31_2006"

Thank you in advance!

 
Reply With Quote
 
 
 
 
Robert Klemme
Guest
Posts: n/a
 
      05-31-2006
Tim Hoolihan wrote:
> sorry that regular expression should have been
>
> return unclean.gsub(/[^A-Z,a-z,0-9, ]+?/,"_")


No. Commas are no meta characters in character classes:

>> ",".gsub(/[^A-Z,a-z,0-9, ]+?/,"_")

=> ","

You rather want

>> ",".gsub(/[^A-Za-z0-9]+?/,"_")

=> "_"

Alternatively this may work as well

>> ",".gsub(/\W/,"_")

=> "_"

Cheers

robert
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
How to truncate char string fromt beginning and replace chars instring by other chars in C or C++? Hongyu C++ 9 08-08-2008 12:18 PM
Floats to chars and chars to floats Kosio C Programming 44 09-23-2005 09:49 AM
receiving ??? chars instead of "special" chars M.Posseth ASP .Net Web Services 3 11-16-2004 07:00 PM
easy way to remove nonprintable chars from string Don Hiatt Python 3 07-24-2003 08:47 PM
RE: easy way to remove nonprintable chars from string sismex01@hebmex.com Python 0 07-24-2003 08:11 PM



Advertisments