0

Is there any common/standard way to check if string contain at least one alphabetic and one numeric char. Like in this cases:

 checkString("AAAA") = false
 checkString("A2B2") = true
 checkString("2222") = false

I wanted to use StringUtils.isAlphanumeric() but in this case: StringUtils.isAlphanumeric("AAAA") it gives true. I know that it can be written with iteration over chars, but maybe there is some other way to do this.

lczapski
  • 4,026
  • 3
  • 16
  • 32
  • 1
    yes, a simple regex would do the trick – Stultuske Feb 11 '21 at 12:17
  • As per java doc `Returns: true if only contains letters or digits, and is non-null` http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isAlphanumeric-java.lang.CharSequence- – Kaustubh Khare Feb 11 '21 at 12:20
  • I'm afraid that iteration is the way to go here... – Serge Ballesta Feb 11 '21 at 12:22
  • @Stultuske if you try to implement a simple RegEx you would know how complex regex could be. If performance is critical then you should avoid regex and work with the classic way over chars. –  Feb 11 '21 at 12:23
  • Does this answer your question? [Fastest way to check a string is alphanumeric in Java](https://stackoverflow.com/questions/12831719/fastest-way-to-check-a-string-is-alphanumeric-in-java) – Kaustubh Khare Feb 11 '21 at 12:27

2 Answers2

1

You can definitely use some fancy ways to check this, like regular expressions. But I just recommend using iteration over chars for things like that.

Iteration is very easy-to-read, everyone can understand this, even junior developers who never seen Java before.

Also, a simple iteration like that is extremely fast and can be optimized with JIT-compilers.

You don't have to use a rocket launcher to kill a fly :-)

Oleg Chirukhin
  • 970
  • 2
  • 7
  • 22
0

Iteratre over each character of the string, and check for each one if it is Alpha or Numeric. You can declare two bool variables to hold the result. Example:

foundAlpha = false
foundNumeric = false

Whenever you find a numeric or an alpha character, change the corresponding bool variable from above. Then by the end of the iterations, check if foundAlpha && foundNumeric is True.

Daniel Reyhanian
  • 579
  • 4
  • 26