Ruby-alphanumeric verification

I would like to verify that the foo variable in Ruby is not empty and alphanumeric. I know that I could go through each character and check, but the best way to do this?

+6
source share
1 answer

Using Unicode or POSIX Character Classes

To verify that a string matches only alphanumeric text, you can use an attached character class. For instance:

 # Use the Unicode class. 'foo' =~ /\A\p{Alnum}+\z/ # Use the POSIX class. 'foo' =~ /\A[[:alnum:]]+\z/ 

Reinforcement is the main

The importance of reinforcing your expression cannot be overestimated. Without binding, the following would also be true:

 "\nfoo" =~ /\p{Alnum}+/ "!foo!" =~ /\p{Alnum}+/ 

which is unlikely to be what you expect.

+15
source

All Articles