Search code examples
javastringarraylistindexof

How to check if a string matches a specific expression?


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.


Solution

  • 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.