Ruby-on-rails 如何从字符串中去除非字母数字字符并保留空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6104240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I strip non alphanumeric characters from a string and keep spaces?
提问by TheExit
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?
这里的问题是它删除了所有空格。如何保留空间的解决方案?
回答by jwueller
Add spaces to the negated character group:
向否定字符组添加空格:
@search_query = @search_query.gsub(/[^0-9a-z ]/i, '')
回答by nvugteveen
In this case I would use the bang method (gsub! instead of gsub) in order to clean the input permanently.
在这种情况下,我将使用 bang 方法(gsub!而不是 gsub)来永久清理输入。
#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.
这避免了在代码中的其他地方使用 @seach_query 而没有清理它的情况。
回答by Vadym Tyemirov
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
回答by piton4eg
Maybe this will work for such case:
也许这适用于这种情况:
# do not replace any word characters and spaces
@search_query = @search_query.gsub(/[^\w ]/g, '')
回答by John Doe
A better answer (at least in ruby) is:
更好的答案(至少在 ruby 中)是:
@search_query.gsub!(/^(\w|\s*)/,'')

