# Regular expression question

**URL:** <https://www.ruby-forum.com/t/regular-expression-question/196726>\
**Category:** Ruby\
**Created:** [June 26, 2008, 12:39am UTC](https://www.ruby-forum.com/t/regular-expression-question/196726 "2008-06-26T00:39:19Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![staypufd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecd19e/32.png) [@staypufd](https://www.ruby-forum.com/u/staypufd)\
**Post date:** [June 26, 2008, 12:39am UTC](https://www.ruby-forum.com/t/regular-expression-question/196726/1 "2008-06-26T00:39:19Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![staypufd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecd19e/32.png) [@staypufd](https://www.ruby-forum.com/u/staypufd)\
**Post date:** [June 26, 2008, 2:32am UTC](https://www.ruby-forum.com/t/regular-expression-question/196726/2 "2008-06-26T02:32:14Z")

</div>

On Wed, Jun 25, 2008 at 6:37 PM, Sam G. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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](http://LearnRuby.com) offers Rails & Ruby HANDS-ON public & ON-SITE workshops.  
Please visit [http://LearnRuby.com](http://LearnRuby.com) for all the details.

---

<div class="post-metadata">

**Author:** ![staypufd](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ecd19e/32.png) [@staypufd](https://www.ruby-forum.com/u/staypufd)\
**Post date:** [June 27, 2008, 9:05am UTC](https://www.ruby-forum.com/t/regular-expression-question/196726/3 "2008-06-27T09:05:06Z")

</div>

2008/6/26 Eric I. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> 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
