Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby alphanumeric check

Tags:

regex

ruby

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?

like image 364
Mika H. Avatar asked Nov 12 '12 01:11

Mika H.


1 Answers

Use Unicode or POSIX Character Classes

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/

Anchoring is Essential

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.

like image 67
Todd A. Jacobs Avatar answered Sep 27 '22 18:09

Todd A. Jacobs