settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Match Full Name - Java Task (RegEx)

+9 votes

Write a regular expression to match a valid full name. A valid full name consists of two words, each word starts with a capital letter and contains only lowercase letters afterwards; each word should be at least two letters long; the two words should be separated by a single space.

Examples:

Match ALL of these

Match NONE of these

Ivan Ivanov

ivan ivanov, Ivan ivanov, ivan Ivanov, IVan Ivanov, Ivan IvAnov, Ivan      Ivanov

 

Input

Output

ivan ivanov

Ivan Ivanov

end

Ivan Ivanov

 

asked in Java category by user paulcabalit

1 Answer

+1 vote
 
Best answer

To help you out, here are some several steps:

  • Use an online regex tester like https://regex101.com/
  • Check out how to use character sets (denoted with square brackets - "[]")
  • Specify that you want two words with a space between them (the space character ' ', and not any whitespace symbol)
  • For each word, specify that it should begin with an uppercase letter using a character set. The desired characters are in a range – from 'A' to 'Z'.
  • For each word, specify that what follows the first letter are only lowercase letters, one or more – use another character set and the correct quantifier.
  • To prevent capturing of letters across new lines, put "\b" at the beginning and at the end of your regex. This will ensure that what precedes and what follows the match is a word boundary (like a new line).
  • In order to check your regex, use these values for reference (paste all of them in the Test String field)

Here is the code:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Pr_01_MatchFullName {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        String input;

        String regex = "(\\b[A-Z]{1}[a-z]+)( )([A-Z]{1}[a-z]+\\b)";
        Pattern pattern = Pattern.compile(regex);

        while (!(input = scanner.nextLine()).equals("end")) {
            Matcher matcher = pattern.matcher(input);
            if (matcher.find()) {
                System.out.println(input);
            }
        }
    }
}
answered by user hues
edited by user golearnweb
...