Shilpi Agrawal
Shilpi Agrawal

Reputation: 615

Regex to check if string is just made up of special characters

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

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

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

Related Questions