开发者

How to check string contains special character in ruby

How to check whether a string contains special character in ruby. If I get regular expression also it is fine.

Plea开发者_如何学Pythonse let me know


Use str.include?.

Returns true if str contains the given string or character.

"hello".include? "lo"   #=> true
"hello".include? "ol"   #=> false
"hello".include? ?h     #=> true


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:

/[<every character in special, escaped>]/


"foobar".include?('a')
# => true


Why not use inverse of [:alnum:] posix.

Here [:alnum:] includes all 0-9, a-z, A-Z.

Read more here.


"Hel@lo".index( /[^[:alnum:]]/ )

This will return nil in case you do not have any special character and hence eaiest way I think.


How about this command in Ruby 2.0.0 and above?

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

Therefore, with:

!"He@llo"[/\W/].nil?  => True

!"Hello"[/\W/].nil?   => False


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜