[英]Regular expression to validate a name
I'm trying to create a regex that satisfies the following:我正在尝试创建一个满足以下条件的正则表达式:
Here's what I got so far:这是我到目前为止得到的:
^[A-Z][a-zA-z ]{1,29}$
If I put a [^ ] at the end, it allows a special character.如果我把 [^ ] 放在最后,它允许一个特殊字符。
You can use您可以使用
^[A-Z](?=.{1,29}$)[A-Za-z]*(?:\h+[A-Z][A-Za-z]*)*$
The pattern matches:模式匹配:
^
Start of string ^
字符串开头[AZ]
Match an uppercase char AZ [AZ]
匹配大写字符 AZ(?=.{1,29}$)
Assert 1-29 chars to the right till the end of the string (?=.{1,29}$)
将 1-29 个字符插入到字符串的末尾[A-Za-z]*
Optionally match a char A-Za-z [A-Za-z]*
可选择匹配一个字符 A-Za-z(?:\h+[AZ][A-Za-z]*)*
Optionally repeat 1+ horizontal whitespace chars followed by again an uppercase char AZ and optional chars A-Za-z (?:\h+[AZ][A-Za-z]*)*
可选择重复 1+ 个水平空白字符,后跟一个大写字符 AZ 和可选字符 A-Za-z$
End of string $
字符串结尾In Java with the doubled backslashes在带有双反斜杠的 Java 中
String regex = "^[A-Z](?=.{1,29}$)[A-Za-z]*(?:\\h+[A-Z][A-Za-z]*)*$";
var pattern = Pattern.compile("^((?=.{1,29}$)[A-Z]\\w*(\\s[A-Z]\\w*)*)$");
var matcher = pattern.matcher("Multiple Words With One Space Separator");
System.out.println(matcher.matches()); // false
matcher = pattern.matcher("Multiple Words");
System.out.println(matcher.matches()); // true
String regex = "[A-Z](?=.{1,29}$)[A-Za-z]{1,}([ ][A-Z][A-Za-z]{1,})*";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.