简体   繁体   中英

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)
  • 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
  • (?=.{1,29}$) Assert 1-29 chars to the right till the end of the string
  • [A-Za-z]* Optionally match a char 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
  • $ End of string

Regex demo

In Java with the doubled backslashes

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,})*";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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