• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Pattern Match For ALphanumeric  RSS feed

 
chitra lekha
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I need to validate whether the given string is alphanumeric or not and take the decision based on it.
I am using java pattern for the same with regex.

Pattern p = Pattern.compile("^[A-Za-z0-9]+$");
p.matcher(s).matches()

It shud return false if the string passed contains only number or only letters or any special charaters.

And true if the string contains both numeric and letters present in any order.

However with above pattern its returning true when I am entering "234" or "abcd".

Please let me know what should be the regular expression used here.
 
Balagopal Kannampallil
Ranch Hand
Posts: 136
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This link has a similar problem and solution discussed.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ASCII only? Or can there be accented characters?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Personally, I would probably not try to write a single regex to do it all...I'd make several tests in separate methods.

If your requirements change in a week or a month, it's much easier to add or delete them that way than by coming up with one convoluted expression. Something like

doesContainAlpha()
doesContainNum()
onlyContainAlphanum()

all these would return a boolean, then my if-condition would work of those results.

 
Richard Tookey
Bartender
Posts: 1166
17
Java Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My approach would be to use


or
 
chitra lekha
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Richard,

Thanks a lot got the solution to my problem. This is the solution which I have used.

Pattern p = Pattern.compile("(?=.*[0-9])" // There is a digit
+ "(?=.*[a-zA-Z])" // there is a letter
+ "[a-zA-Z0-9]*");
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Richard Tookey wrote:My approach would be to use...

Same concept...the different tests are still separated out, so they can easily be changed/added to/amended when the requirements change.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!