This seems to work. There's probably a cleaner way with a single regex, and, honestly, it would be clearer just to use 2 different regexes--one that says "contains at least one letter" and one that says "contains at least one digit", and then test that it matches regex1 AND matches regex2.
Breaking it apart:
The idea is that if there's at least one digit and at least one letter, and all characters are either digit or letter, then somewhere we must have either digit followed by letter or letter followed by digit. It could be at the beginning, the middle, or the end, so the "either/or" character classes have to have the zero-or-more qualifier. That is, zero characters then LN or NL, or some Ls and/or Ns followed by LN or NL, then zero or more Ls and/or Ns.
Also note that if you're using String.matches() or Matcher.matches(), you don't need the ^ and $, since matches() attempts to match against the entire input anyway.
Joined: Jan 25, 2012
Great, this works like magic!! Thank you very much Jeff, for a very quick response!
Be warned, though, I expect it runs pretty slowly. If you're doing a large number of tests in a row, or testing against a very large input, it might be a problem. In that case, you'll have to either find somebody who's better at regex than I, or just break it into two separate tests (or perhpas 3) like I suggested.
Joined: Jan 25, 2012
Got it, it is not a very high volume scenario, so this should be good. One other question. Since this solution is internationalized, I'm trying to test with unicode characters. Do you know any site where I can get good unicode character set to test this with?
Sri Ponnapalli wrote:Sorry Darryl, I wasn't aware of the cross-posting rules. Will certainly play by the rules in future.
Thanks again Jeff, your answer DID help me a lot! (I didn't hear on any of the other forums)
You're welcome! Glad I could help!
Please go back to the other forums and let them know that it's been answered (so people don't waste their time) and provide a link to this one in case anybody is interested in the solution, or wants to improve on it.