Stripping non-alphanumeric chars but leaving spaces in Ruby

Some fine solutions, but simplest is usually best:

string.downcase.gsub /\W+/, ' '

If you want to catch non-latin characters, too:

str = "The basketball-player is great! (Kobe Bryant) (ひらがな)"
str.downcase.gsub(/[^[:word:]\s]/, '')
#=> "the basketballplayer is great kobe bryant ひらがな"

You can simply add \s (whitespace)

string.downcase.gsub(/[^a-z0-9\s]/i, '')


All the other answers strip out numbers as well. That works for the example given but doesn't really answer the question which is how to strip out non-alphanumeric.

string.downcase.gsub(/[^\w\s]/, '')

Note this will not strip out underscores. If you need that then:

string.downcase.gsub(/[^a-zA-Z\s\d]/, '')

Tags:

String

Ruby