可以使用java.util.regex.Pattern.matches()方法来验证名称。此方法将名称和给定输入名称的正则表达式匹配,如果匹配则返回true,否则返回false。
演示此过程的程序如下:
public class Demo { public static void main(String args[]) { String name = "John Harry Smith"; String regexName = "\\p{Upper}(\\p{Lower}+\\s?)"; String patternName = "(" + regexName + "){2,3}"; System.out.println("The name is: " + name); System.out.println("Is the above name valid? " + name.matches(patternName)); } }
输出结果
The name is: John Harry Smith Is the above name valid? true
现在让我们了解上面的程序。
名称已打印。Pattern.matches()方法将名称和给定输入名称的正则表达式匹配,并打印结果。演示此代码段如下:
String name = "John Harry Smith"; String regexName = "\\p{Upper}(\\p{Lower}+\\s?)"; String patternName = "(" + regexName + "){2,3}"; System.out.println("The name is: " + name); System.out.println("Is the above name valid? " + name.matches(patternName));