I am trying to validate a String
which contains the first & last name of a person. The acceptable formats of the names are as follows.
Bruce Schneier
Schneier, Bruce
Schneier, Bruce Wayne
O’Malley, John F.
John O’Malley-Smith
Cher
I came up with the following program that will validate the String variable. The validateName
function should return true
if the name format matches any of the mentioned formats able. Else it should return false
.
import java.util.regex.*;
public class telephone {
public static boolean validateName (String txt){
String regx = "^[\\\\p{L} .'-]+$";
Pattern pattern = Pattern.compile(regx, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(txt);
return matcher.find();
}
public static void main(String args[]) {
String name = "Ron O’’Henry";
System.out.println(validateName(name));
}
}
But for some reason, it is returning false
for any value. What am I doing wrong here?
Use this:
^[\p{L}\s.’\-,]+$
Demo: https://regex101.com/r/dQ8fK8/1
'
and ’
is different. You can only achieve that character by copy pasting from the text.\-
instead of -
in []
since it will be mistaken as a range. For example: [a-z]
\s
instead of
for matching any whitespaces.You can do:
^[^\s]+,?(\s[^\s]+)*$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With