Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Please let me know

like image 462
Shrikanth Hathwar Avatar asked Jun 14 '11 12:06

Shrikanth Hathwar


People also ask

How do I remove special characters from a string in Ruby?

In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.

Where do I find substrings in Ruby?

There is no substring method in Ruby, and hence we rely upon ranges and expressions. If we want to use the range, we have to use periods between the starting and ending index of the substring to get a new substring from the main string.

What does =~ mean in Ruby?

=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.

How do you get the first 3 characters of a string in Ruby?

To access the first n characters of a string in ruby, we can use the square brackets syntax [] by passing the start index and length. In the example above, we have passed the [0, 3] to it. so it starts the extraction at index position 0 , and extracts before the position 3 .


5 Answers

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
like image 190
Rishabh Avatar answered Oct 19 '22 16:10

Rishabh


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>]/
like image 43
Max Williams Avatar answered Oct 19 '22 15:10

Max Williams


"foobar".include?('a')
# => true
like image 6
Jakob S Avatar answered Oct 19 '22 15:10

Jakob S


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

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

like image 3
Akshat Avatar answered Oct 19 '22 15:10

Akshat


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
like image 1
Nikesh Avatar answered Oct 19 '22 16:10

Nikesh