如何从字符串中去除非字母数字字符并保留空格?

我想创建一个正则表达式,删除所有非字母数字字符,但保留空格。这是为了在搜索输入到数据库之前清理它。以下是我目前掌握的信息:

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

这里的问题是它删除了所有的空格。如何保留空格的解决方案?

74124 次浏览

Add spaces to the negated character group:

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

A better answer (at least in ruby) is:

@search_query.gsub!(/^(\w|\s*)/,'')

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.

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

Maybe this will work for such case:

# do not replace any word characters and spaces
@search_query = @search_query.gsub(/[^\w ]/g, '')