Search code examples
rubyregexrubular

Ruby Regex Rubular vs reality


I have a string and I want to remove all non-word characters and whitespace from it. So I thought Regular expressions would be what I need for that.

My Regex looks like that (I defined it in the string class as a method):

/[\w&&\S]+/.match(self.downcase)

when I run this expression in Rubular with the test string "hello ..a.sdf asdf..," it highlioghts all the stuff I need ("hellloasdfasdf") but when I do the same in irb I only get "hello".

Has anyone any ideas about why that is?


Solution

  • Because you use match, with returns one matching element. If you use scan instead, all should work properly:

    string = "hello ..a.sdf asdf..,"
    string.downcase.scan(/[\w&&\S]+/)
    # => ["hello", "a", "sdf", "asdf"]