7

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?

Pablo Fernandez heelhook
  • 11,985
  • 3
  • 21
  • 20
Mika H.
  • 4,119
  • 11
  • 44
  • 60

1 Answers1

17

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.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • +1 This takes into account all sorts of characters beyond `A-Za-z0-9`, which is a good thing. – the Tin Man Nov 12 '12 at 01:53
  • What does the operator `=~` do? I've never seen it before. – Mika H. Nov 12 '12 at 02:13
  • 1
    @MikaH. It's the regular expression pattern match operator. See http://stackoverflow.com/a/5781400/1301972 or http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html for more on this operator. – Todd A. Jacobs Nov 12 '12 at 02:17
  • For an explaination about anchoring https://web.archive.org/web/20180813034209/https://batsov.com/articles/2013/12/04/regexp-anchors-in-ruby/ – Jérôme Sep 23 '21 at 10:15