To validate names that can be
John, John Paul, etc.
I use this regex:
String regex = "[A-Z]([a-z]+|\\s[a-z]+)";
but when I do:
boolean ok = Pattern.matches(regex, "John Paul");
the matches fail?
Why? I want to use matches to validate the string as whole…
Is that regex wrong?
Try something like this:
The
?is an optional part that matches the last name. This captures the last name (with a preceding space) in group 1. You can use a non-capturing group(?:...)if you don’t need this capture.References
Problem with original pattern
Here’s the original pattern:
Expanding the alternation this matches:
Or:
This does match
John, andJ paul, but it clearly doesn’t matchJohn Paul.