Regex Replacement in Ruby

I'm stumped at to why Ruby's gsub() method works the way it does. Take a look at this following snippet.

(Update: I grabbed the pattern directly from the Pragmatic Rails book, not realizing it was a typo.)

value1 = "3 3 393923 2932--3 2939"
value2 = value1.clone
value3 = value1.clone

value1.gsub!(/[\w]/, '')  
puts "'#{value1}'"

value2.gsub!(/[^\w]/, '')
puts "'#{value2}'"

value3.gsub!(/[^\d]/, '')
puts "'#{value3}'"


The result is this:

'   -- '
'33393923293232939'
'33393923293232939'


I would have really expected the first one would work, as I'd be describing the pattern that I want to replace. Instead, for it seems that I have to negate the whitespace that I want to replace. Also, why is it that hyphens are considered whitespace?
Design Element
Regex Replacement in Ruby
Posted Oct 30, 2005 — 3 comments below




 

Elliott Hughes — Oct 30, 05 481

\w means "word", not whitespace. you meant \s.

Scott Stevenson — Oct 30, 05 482 Scotty the Leopard

Doh. You're right. I grabbed the pattern from the Pragmatic Rails book (page 276), but I should have realized it was wrong anyway.

Pancho — Nov 09, 05 527

Ruby SUX anyway... Lets do asma!




 

Comments Temporarily Disabled

I had to temporarily disable comments due to spam. I'll re-enable them soon.





Copyright © Scott Stevenson 2004-2015