114

I want to create a regex that removes all non-alphanumber characters but keeps spaces. This is to clean search input before it hits the db. Here's what I have so far:

@search_query = @search_query.gsub(/[^0-9a-z]/i, '')

Problem here is it removes all the spaces. Solutions on how to retain spaces?

jwueller
  • 30,582
  • 4
  • 66
  • 70
TheExit
  • 5,220
  • 12
  • 37
  • 49

5 Answers5

206

Add spaces to the negated character group:

@search_query = @search_query.gsub(/[^0-9a-z ]/i, '')
jwueller
  • 30,582
  • 4
  • 66
  • 70
14

In this case I would use the bang method (gsub! instead of gsub) in order to clean the input permanently.

#permanently filter all non-alphanumeric characters, except _
@search_query.gsub!(/\W/,'')

This avoids a situation where @seach_query is used elsewhere in the code without cleaning it.

nvugteveen
  • 496
  • 3
  • 6
  • 2
    The bang version will return nil if nothing was matched. Probably not the result you'd want or expect. From the docs _"Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed. If no block and no replacement is given, an enumerator is returned instead."_ – dft Jan 20 '16 at 06:45
  • 2
    In his example the return value isn't used, so that's pretty much irrelevant. – Jaap Haagmans Mar 22 '17 at 08:36
3

I would have used the inclusion approach. Rather than exclude all but numbers, I would only included numbers. E.g.

@search_query.scan(/[\da-z\s]/i).join
Travis
  • 13,311
  • 4
  • 26
  • 40
Vadym Tyemirov
  • 8,288
  • 4
  • 42
  • 38
0

Maybe this will work for such case:

# do not replace any word characters and spaces
@search_query = @search_query.gsub(/[^\w ]/g, '')
piton4eg
  • 1,096
  • 2
  • 10
  • 21
-3

A better answer (at least in ruby) is:

@search_query.gsub!(/^(\w|\s*)/,'')
John Doe
  • 199
  • 1
  • 8
  • 2
    This is going to remove either (a) a single word character or (b) any number of whitespace from the beginning of the string. Completely unrelated to the question, and therefore not an answer. – Sigi May 04 '14 at 19:48
  • 2
    made a big mistake .. don't know what i was thinking :=( – John Doe May 10 '14 at 19:03