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 (?=.{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 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.