[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

regular expression question

Sam Ginko

6/25/2008 10:37:00 PM

I'm trying to replace all characters that are not letters numbers and
white spaces in a string. I'm getting the characters eliminated in this
case a comma but the white space is eliminated to. How do I get around
that?


string = 'john, tony'
newTerms = string.gsub(/\W/, "")


thanks
--
Posted via http://www.ruby-....

2 Answers

Eric I.

6/26/2008 12:27:00 AM

0

On Wed, Jun 25, 2008 at 6:37 PM, Sam Ginko <ginkod@gmail.com> wrote:
> I'm trying to replace all characters that are not letters numbers and
> white spaces in a string. I'm getting the characters eliminated in this
> case a comma but the white space is eliminated to. How do I get around
> that?
>
>
> string = 'john, tony'
> newTerms = string.gsub(/\W/, "")

I think this does what you want, provided underscores are OK.

newTerms = string.gsub(/[^\w\s]/, "")

If underscores are not OK, then you'll need to change "\w" into "A-Za-z0-9".

Eric

====

LearnRuby.com offers Rails & Ruby HANDS-ON public & ON-SITE workshops.
Please visit http://Lea... for all the details.

Robert Klemme

6/27/2008 7:02:00 AM

0

2008/6/26 Eric I. <rubytraining@gmail.com>:
> On Wed, Jun 25, 2008 at 6:37 PM, Sam Ginko <ginkod@gmail.com> wrote:
>> I'm trying to replace all characters that are not letters numbers and
>> white spaces in a string. I'm getting the characters eliminated in this
>> case a comma but the white space is eliminated to. How do I get around
>> that?
>>
>>
>> string = 'john, tony'
>> newTerms = string.gsub(/\W/, "")
>
> I think this does what you want, provided underscores are OK.
>
> newTerms = string.gsub(/[^\w\s]/, "")
>
> If underscores are not OK, then you'll need to change "\w" into "A-Za-z0-9".

This is usually more efficient:

newTerms = string.gsub(/[^\w\s]+/, "")

Note the "+".

Kind regards

robert

--
use.inject do |as, often| as.you_can - without end