Home > database >  How to check if a string matches a specific expression?
How to check if a string matches a specific expression?

Time:03-09

I want to write a method that check if a string matches the following format: "Name Surname" in Java. There will be max one space between Name and Surname, and both the starting letter of name and surname should be in capital letters.

Here is what I did:

public static Boolean correctFormat(ArrayList<String> e) 
   { 
       int x = 0; 
       for(int i = 0; i < e.size(); i  ) 
       { 
           if (e.get(i).indexOf(" ") != -1 && str.substring() 
           { 
               x  ; 
           } 
           
  }  

However, I could not find a way to check if name and surname's starting letter capital. Name and surname length can vary.

Note: The parameter of the method is ArrayList, so it takes ArrayList as an input.

CodePudding user response:

you can use string split and character.isuppercase() and looping process to solve your issue as shown below

public class Test {

    public static boolean validateString(String string){
        String[] stringArray = string.split(" ");
        if(null == string || stringArray.length>2 || stringArray.length == 1) return false;
        for(String s : stringArray){
            if(!(Character.isUpperCase(s.toCharArray()[0])))return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String s  = "Hello World";
        List<String> names = new ArrayList<>();
        names.add(s);
        names.forEach(string -> System.out.println("Is the string " string " valid :"  validateString(s)));
        
    }
    
}

output : Is the string Hello World valid :true

CodePudding user response:

You may use regex to check your conditions and iterate through your ArrayList using for-each loop.

    public static Boolean correctFormat(ArrayList<String> e)
    {
        String camelCasePattern = "([A-Z][a-z]  [A-Z][a-z] )";
        for(String s : e)
            if(!s.matches(camelCasePattern))
                return false;
        return true;
    }

The above code will return true only when all elements in ArrayList e will match as per the defined pattern.

  • Related