How to check string format without using regular expressions?

Carlos De la Torre :

I'm working on a project where I need to check if a string is in the correct format ABC1234 meaning 3 letters followed by 4 numbers. I was told not to use regular expressions to solve this.

I came up with the following code but it's clunky so I'm looking for something cleaner and more efficient.

String sample = ABC1234

char[] chars = sample.toCharArray();

if(Character.isLetter(chars[0]) && Character.isLetter(chars[1]) && 
   Character.isLetter(chars[2]) && Character.isDigit(chars[3]) && 
   Character.isDigit(chars[4]) && Character.isDigit(chars[5]) && 
   Character.isDigit(chars[6])){

    list.add(sample);
}

// OUTPUT: ABC1234 gets added to "list". When it prints, it appears as ABC1234.

All outputs are as expected but I know this can be done either more efficiently or just better in general.

I'm just checking the first 3 chars to verify they're each a letter and the last 4 chars should be numbers.

Any advice? Thanks in advance.

Pradip Karki :

Here is another way.

String sample = "ABC1234";
if (sample.substring(0, 3).chars().allMatch(Character::isLetter)
      && sample.substring(3).chars().allMatch(Character::isDigit)) {
  list.add(sample);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=73861&siteId=1