如何检查字符串是否包含 ruby 中的特殊字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6343257/
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 to check string contains special character in ruby
提问by Shrikanth Hathwar
How to check whether a string contains special character in ruby. If I get regular expression also it is fine.
如何检查字符串是否包含 ruby 中的特殊字符。如果我得到正则表达式也没关系。
Please let me know
请告诉我
采纳答案by Max Williams
special = "?<>',?[]}{=-)(*&^%$#`~{}"
regex = /[#{special.gsub(/./){|char| "\#{char}"}}]/
You can then use the regex to test if a string contains the special character:
然后,您可以使用正则表达式来测试字符串是否包含特殊字符:
if some_string =~ regex
This looks a bit complicated: what's going on in this bit
这看起来有点复杂:这一点发生了什么
special.gsub(/./){|char| "\#{char}"
is to turn this
是把这个
"?<>',?[]}{=-)(*&^%$#`~{}"
into this:
进入这个:
"\?\<\>\'\,\?\[\]\}\{\=\-\)\(\*\&\^\%\$\#\`\~\{\}"
Which is every character in special, escaped with a \(which itself is escaped in the string, ie \\not \). This is then used to build a regex like this:
这是特殊的每个字符,用 a 转义\(它本身在字符串中转义,即\\not \)。然后使用它来构建这样的正则表达式:
/[<every character in special, escaped>]/
回答by Rishabh
Use str.include?.
使用str.include?.
Returns trueif strcontains the given string or character.
返回true是否str包含给定的字符串或字符。
"hello".include? "lo" #=> true
"hello".include? "ol" #=> false
"hello".include? ?h #=> true
回答by Jakob S
"foobar".include?('a')
#?=> true
回答by Akshat
回答by Nikesh
How about this command in Ruby 2.0.0 and above?
这个命令在 Ruby 2.0.0 及更高版本中怎么样?
def check_for_a_special_charachter(string)
/\W/ === string
end
Therefore, with:
因此,与:
!"He@llo"[/\W/].nil? => True
!"Hello"[/\W/].nil? => False
回答by tony byamungu
if you looking for a particular character, you can make a range of characters that you want to include and check if what you consider to be a special character is not part of that arsenal
如果您正在寻找特定字符,您可以制作一系列您想要包含的字符,并检查您认为的特殊字符是否不属于该武器库的一部分
puts String([*"a".."z"].join).include? "a" #true
puts String([*"a".."z"].join).include? "$" #false
I think this is flexible because here you are not limited as to what should be excluded
我认为这是灵活的,因为在这里您不受限于应该排除的内容
puts String([*"a".."z",*0..9,' '].join).include? " " #true
回答by Akshat
"Hel@lo".index( /[^[:alnum:]]/ )
This will return nilin case you do not have any special character and hence eaiest way I think.
nil如果您没有任何特殊字符,这将返回,因此我认为最简单的方法。

