regular expression question

S

Sam Ginko

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
 
E

Eric I.

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://LearnRuby.com for all the details.
 
R

Robert Klemme

2008/6/26 Eric I. said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,140
Latest member
SweetcalmCBDreview
Top