0

I have to validate name using regex with the following conditions:

1.The Name should contain at least 1 word of length at least 3.

  1. If there are more than 1 word then each word should be separated by single space and should not be empty.

The first part can be done as : [a-bA-Z]{3,}+ There are following constraints for the second one:

  1. If there is only one word no extra space after the word should be included.

  2. After the space there can be any number of characters.

Can anyone help me on this?

1 Answer 1

3

I think this meets your requirements:

^[A-Za-z]{3,}(?: [A-Za-z]+)*$

Reading this out loud, the above pattern says to match at least one word of length 3 or more, which if alone should not be followed by whitespace. If two or more futher words be in the name, they should be separated by a single space.

Sign up to request clarification or add additional context in comments.

4 Comments

Sweet, I was thinking maybe using \p{L} in case you'd encounter some funky names with non-ascii characters =). Would not be uncommon over where I'm from.
I understand the first half. But what does (?: [A-Za-z]+)*$ mean?
It means match space followed by a name, zero or more times. The ?: inside the parentheses just tells the regex engine not to bother capturing anything. Search SO on this if you have more doubts.
Got it. Thanks a lot for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.