I'd like to check that a variable foo
in Ruby is non-empty and alphanumeric. I know I could iterate through each character and check, but is that a better way to do it?
To validate that a string matches only alphanumeric text, you could use an anchored character class. For example:
# Use the Unicode class.
'foo' =~ /\A\p{Alnum}+\z/
# Use the POSIX class.
'foo' =~ /\A[[:alnum:]]+\z/
The importance of anchoring your expression can't be overstated. Without anchoring, the following would also be true:
"\nfoo" =~ /\p{Alnum}+/
"!foo!" =~ /\p{Alnum}+/
which is unlikely to be what you expect.
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