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[A-Z]
Match an uppercase char A-Z(?=.{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+[A-Z][A-Za-z]*)*
Optionally repeat 1+ horizontal whitespace chars followed by again an uppercase char A-Z and optional chars A-Za-z$
End of stringIn Java with the doubled backslashes
String regex = "^[A-Z](?=.{1,29}$)[A-Za-z]*(?:\\h+[A-Z][A-Za-z]*)*$";