Home > Software engineering >  How to check 3rd is dash and first 2 are numbers?
How to check 3rd is dash and first 2 are numbers?

Time:10-23

I have below string

11-abzw9rk

Here first 2 always going to be digit and then after -.

How I validate that first 2 always digit containing -.

Ofcourse can use .contains() but is there any better way to validate digit as well?

CodePudding user response:

Here is a simple version that uses String.charAt() and Character.isDigit()

String str = "11-abzw9rk";

//How to check 3rd is dash
if(str.charAt(2) == '-') {
    System.out.println("Yes, 3rd character is dash");
}

//and first 2 are numbers?
if(Character.isDigit(str.charAt(0)) && Character.isDigit(str.charAt(1))) {
    System.out.println("Yes, first two are digits");
}

CodePudding user response:

Use regex ^\\d{2}-

^ beginning of line

\\d{2} two digits

- dash

.* anything else

import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
Pattern pattern = Pattern.compile("^\\d{2}-.*");
Matcher matcher = pattern.matcher("11-abzw9rk");
boolean matchFound = matcher.find();
if(matchFound) {
  System.out.println("Match found");
} else {
  System.out.println("Match not found");
}

CodePudding user response:

We can check all conditions in one if statement using charAt function of strings. For example s is your string then the condition will be as follows :

  if(Character.isDigit(s.charAt(0)) && Character.isDigit(s.charAt(1)) && s.charAt(2)=='-'){
    System.out.println("Match found");}
else{
    System.out.println("String doesn't match");
}

CodePudding user response:

class Stringcheck{  
     public static void main(String[] args)  {  
         Scanner sc= new Scanner(System.in); 
         System.out.print("Enter the string: ");  
         String str= sc.nextLine();               
         if(Character.isDigit(str.charAt(0)) && Character.isDigit(str.charAt(1)) && 
         (str.charAt(2)=='-'){
              System.out.println("Match found");
          }
         else{
              System.out.println("String doesn't match");
          }          
     }  
}  
  • Related