Why I avoid android.util.Patterns
I wanted to leave a quick note about android.util.Patterns
: I think it's a dangerously misleading class.
It's so tempting - who wouldn't want ready-made, AOSP-approved regexes? But there's some serious problems with Patterns:
-
Regarding
Patterns.EMAIL_ADDRESS
: I'm against using complex regexes to validate emails. It's a surprisingly difficult problem and chances are you will get it wrong. -
Patterns.IP_ADDRESS
only applies to IPv4, so it's misleading. -
Patterns.TOP_LEVEL_DOMAIN
will grow increasingly irrelevant in a world where you can register your own TLDs. -
Both
Patterns.WEB_URL
andPatterns.DOMAIN_NAME
depend onPatterns.TOP_LEVEL_DOMAIN
. Ouch! -
The docs admit that
Patterns.PHONE
is just a heuristic and will miss legitimate phone numbers, so it can't be used for validation.
There are so many caveats to be had with Patterns
that you're better off specifying your own regexes for your use case.