如何检查字符串中包含ruby中的特殊字符

如何检查字符串是否包含ruby中的特殊字符。 如果我得到正则表达式也没关系。

请告诉我

special = "?<>',?[]}{=-)(*&^%$#`~{}" regex = /[#{special.gsub(/./){|char| "\\#{char}"}}]/ 

然后,您可以使用正则表达式来测试字符串是否包含特殊字符:

 if some_string =~ regex 

这看起来有点复杂:这一点发生了什么

 special.gsub(/./){|char| "\\#{char}" 

是转此

 "?<>',?[]}{=-)(*&^%$#`~{}" 

进入这个:

 "\\?\\<\\>\\'\\,\\?\\[\\]\\}\\{\\=\\-\\)\\(\\*\\&\\^\\%\\$\\#\\`\\~\\{\\}" 

哪个是特殊的字符,用\ _进行转义(它本身在字符串中转义,即\\不是\ )。 然后用它来构建这样的正则表达式:

 /[]/ 

使用str.include?

如果str包含给定的字符串或字符,则返回true

 "hello".include? "lo" #=> true "hello".include? "ol" #=> false "hello".include? ?h #=> true 
 "foobar".include?('a') # => true 

为什么不使用[:alnum:] posix的倒数。

这里[:alnum:]包括所有0-9azAZ

在这里阅读更多。

在Ruby 2.0.0及更高版本中,这个命令怎么样?

 def check_for_a_special_charachter(string) /\W/ === string end 

因此,有:

 !"He@llo"[/\W/].nil? => True !"Hello"[/\W/].nil? => False 
 "Hel@lo".index( /[^[:alnum:]]/ ) 

如果你没有任何特殊的角色,那么这将返回nil ,因此我认为是最简单的方式。