简体   繁体   English

用于验证名称的正则表达式

[英]Regular expression to validate a name

I'm trying to create a regex that satisfies the following:我正在尝试创建一个满足以下条件的正则表达式:

  • The length of the name should be between 2 and 30 characters (both inclusive)名称的长度应在 2 到 30 个字符之间(包括两个字符)
  • The name can contain only alphabets and spaces名称只能包含字母和空格
  • The first character of each word of the name should be an upper case alphabet名称的每个单词的第一个字符应为大写字母
  • Each word should be separated by a space每个单词都应该用空格隔开
  • The name should not start or end with a space名称不应以空格开头或结尾
  • Special characters should not be allowed不应允许特殊字符

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 $字符串结尾

Regex demo正则表达式演示

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM