首页 > 解决方案 > Java 正则表达式名称验证

问题描述

请我需要帮助。我正在编写一个用于验证的函数...条件是:*名称长度应在 2 和 30 之间 *每个单词的第一个字母应为大写(Steve Smith 有效;steve Smith 无效或 Steve smith 无效)*每个单词之间应该有空格,名称不应该以空格开头或结尾。

String regex = "([A-Z][A-Za-z]+ )+{2,30}";
    if(name.matches(regex))
      return true;
    return false;

这是用于验证名称的函数中的片段。将感谢您的帮助。先感谢您。

标签: javaregexstring

解决方案


要提取单词以大写开头,然后全部小写 -([A-Z]([a-z]*))

public static boolean isValidIdentifier(String identifier)
{

    // Regex to check valid identifier.
    String regex = "^(?=.{2,20}$)([A-Z]([a-z]*))+(\\s+([A-Z]([a-z]*)))*$";

    // Compile the ReGex
    Pattern p = Pattern.compile(regex);

    // If the identifier is empty
    // return false
    if (identifier == null) {
        return false;
    }

    // Pattern class contains matcher() method
    // to find matching between given identifier
    // and regular expression.
    Matcher m = p.matcher(identifier);

    // Return if the identifier
    // matched the ReGex
    return m.matches();
}

推荐阅读