How to check whether a string contains special character in ruby. If I get regular expression also it is fine.
Please let me know
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.
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.
=~ 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.
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 .
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
"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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With