Ruby Regex error text.gsub [^ \ W-], '') does not work

I am trying to learn Regex in Ruby based on what I read in The Rails Way. But even this simple example surpassed me. I canโ€™t say if this is a typo or not ...

text.gsub (/ \ s /, "-"). gsub ([^ \ W-], '') .downcase

It seems to me that this will replace all spaces with -, then in any case the line starts with a letter or number followed by a dash, replace it with ''. But, using irb, it first fails in a syntax error, unexpected '^', waiting for ']' ", and if I select ^, it will not be on W. again.

I'm pretty confused here.

+6
ruby regex
source share
5 answers
>> text = "I love spaces" => "I love spaces" >> text.gsub(/\s/, "-").gsub(/[^\W-]/, '').downcase => "--" 

Missing//

Although this makes sense :-)

 >> text.gsub(/\s/, "-").gsub(/([^\W-])/, '\1').downcase => "i-love-spaces" 

And that probably means

 >> text.gsub(/\s/, "-").gsub(/[^\w-]/, '').downcase => "i-love-spaces" 

\ W means "not a word" \ w means "a word"

// generate a regexp object

/ [^ \ W -] ./ Class => Regexp

+9
source share

Step 1: Bookmark this . Whenever I need to search for regular expressions, this is my first stop

Step 2: Skip through your code

 text.gsub(/\s/, "-") 

You call the gsub function and provide it with 2 parameters.
The first parameter is /\s/ , which is ruby โ€‹โ€‹for "create new regexp containing \s (// as special" "for regular expressions).
The second parameter is the string "-" .

This will replace all whitespace with hyphens. So far so good.

 .gsub([^\W-], '').downcase 

Then you call gsub again, passing 2 parameters to it. The first parameter is [^\W-] . Since we did not quote it in distortions, the ruby โ€‹โ€‹will literally try to run this code. [] creates an array, and then tries to put ^\W- into the array, which is invalid code, so it breaks.
Changing it to /[^\W-]/ gives the correct regular expression.

Looking at the regular expression, [] says that it matches any character in this group. The group contains \W (which means a non-word character) and - , so the regular expression must match any character other than a word, or any hyphen.

As the second thing you pass to gsub is an empty string, it should eventually replace all characters and hyphens without words with an empty string (thereby deleting them)

 .downcase 

Which only converts the string to lowercase.

Hope this helps :-)

+3
source share

You forgot the slashes. It should be /[^\W-]/

+2
source share

Well, .gsub (/ [^ \ W -] /, '') says it replaces everything that is neither a word nor nothing.

You probably want

 >> text.gsub(/\s/, "-").gsub(/[^\w-]/, '').downcase => "i-love-spaces" 

Lowercase \ w (\ W is just the opposite)

+2
source share

A slash means that the thing between them is a regular expression, just like quotes, there is a line between them.

+1
source share

All Articles