Reputation: 1543
I am given a string (name) and it is supposed to check for the following:
here is my regex string: "[[[A-Z]{1}[a-zA-Z]*[\\s]?+]{2,30}[^\\s]"
"Roger Federer" should be valid, and this says it is "Roger federer" should NOT be valid, but mine says it is "Roger Federer $" should NOT be valid, but mine says it is
I'm curious if I'm enforcing these wrong, I am very new to regex
Upvotes: 1
Views: 1483
Reputation: 626799
You can use
^(?=.{2,30}$)\p{Lu}\p{L}*(?:\s\p{Lu}\p{L}*)*$
If you want to allow one or more whitespaces between words, add +
after \s
.
See the regex demo.
In Java, the regex declaration will look like
s.matches("(?=.{2,30}$)\\p{Lu}\\p{L}*(?:\\s\\p{Lu}\\p{L}*)*")
The pattern matches
^
- (implicit in matches
) - start of string(?=.{2,30}$)
- two to thirty chars required in the whole string\p{Lu}\p{L}*
- an uppercase letter followed with zero or more letters(?:\s\p{Lu}\p{L}*)*
- zero or more occurrences of a whitespace, then an uppercase letter and then zero or more letters$
- (implicit in matches
) - end of string.If you want to only match ASCII letters, replace \p{Lu}
with [A-Z]
and \p{L}
with [A-Za-z]
.
Upvotes: 1