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?
I’d like to check that a variable foo in Ruby is non-empty and alphanumeric.
Share
Use Unicode or POSIX Character Classes
To validate that a string matches only alphanumeric text, you could use an anchored character class. For example:
Anchoring is Essential
The importance of anchoring your expression can’t be overstated. Without anchoring, the following would also be true:
which is unlikely to be what you expect.