Reputation: 55
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.
Upvotes: 0
Views: 5576
Reputation: 1
The above answer didn't work for me fully (in mendix). It didn't satisfy the "at least 2 character long" part, so we came up with this :
^([A-ZÁÉÍÚÜŰÓÖŐ][A-ZÁÉÍÚÜŰÓÖŐa-záéíúüűóöő\-]+)( [A-ZÁÉÍÚÜŰÓÖŐ][A-ZÁÉÍÚÜŰÓÖŐa-záéíúüűóöő\-]+)+$
We added hungarian characters and "-" as it is allowed in Last Name, but for your case you can use this:
^([A-Z][a-z]+)( [A-Z][a-z]+)+$
Upvotes: 0
Reputation: 1
String regex = "[A-Z](?=.{1,29}$)[A-Za-z]{1,}([ ][A-Z][A-Za-z]{1,})*";
Upvotes: 0
Reputation: 2890
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
Upvotes: 0
Reputation: 163577
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]*)*$";
Upvotes: 3