java - 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;
这是用于验证名称的函数中的片段。将感谢您的帮助。先感谢您。
解决方案
要提取单词以大写开头,然后全部小写 -([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();
}
推荐阅读
- python-3.x - 无法在 Python 中查明确切的非类型错误
- java - 使用 LocalServerChannel/LocalChannel 时出现错误 'io.netty.channel.ChannelException: connection denied'?
- javascript - 如何在2个字符串之间获取字符串并添加到数组
- c - CRTDBG Visual Studio 2008 未检测到内存泄漏
- mongodb - Mongoose - 仅填充返回 _id 而不是对象
- arrays - 如何创建一个可排序的长嵌套列表?
- php - 如何在 PhpSpreadsheet 中修复 TcPDF 编写器中的边框?
- sql - Cloud SQL 计费
- json - 如何在没有密钥的情况下访问 JSON 文件的内容?
- kubernetes - 通过 Nodeport 导航到特定路径