Ruby Regex问题text.gsub [^\W-],'')失败

scu*_*bbl 6 ruby regex

我正在尝试在Ruby中学习正则表达式,基于我在"The Rails Way"中阅读的内容.但是,即便是这个简单的例子也让我很难过.我不知道这是不是一个错字......

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

在我看来,这将用 - 替换所有空格,然后字符串以非字母或数字后跟短划线开头,用''代替.但是,使用irb,它首先失败^"语法错误,意外'^',期待']'",如果我取出^,它在W上再次失败.

我在这里很困惑.

Vin*_*vic 9

>> text = "I love spaces"
=> "I love spaces"
>> text.gsub(/\s/, "-").gsub(/[^\W-]/, '').downcase
=> "--"
Run Code Online (Sandbox Code Playgroud)

失踪 //

虽然这更有意义:-)

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

这可能意味着什么

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

\ W表示"不是一个字"\ w表示"一个字"

//生成一个regexp对象

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