Reputation: 615
I have some strings for which i have to check whether it is made up of all special characters in regex i tried something but its not working the way i want any help ?
str = "@#%^"
regex = /[\?\<\>\'\,\?\[\]\}\{\=\-\)\(\*\&\^\%\$\#\`\~\{\}\@]/
str.match(regex)
Upvotes: 2
Views: 2629
Reputation: 627537
You can do it with
/\A\W*\z/
The \W*
matches any non-word character from the beginning (\A
) till the end (\z
) of string.
See demo:
class String
def onlySpecialChars?
!!self.match(/\A\W*\z/)
end
end
puts "@#%^".onlySpecialChars? # true
puts "w@#%^".onlySpecialChars? # false
If you have your own set of special characters, just use instead of \W
. Just also note you have overescaped your regex, [?<>',?\[\]}{=)(*&^%$#`~{}@-]
will suffice.
Upvotes: 3