J.Doe
J.Doe

Reputation: 179

Regular expression for the name

I need to build a regex for a name with the following pattern, so John D.E. would pass the regex test. Basically what I want is:

  1. N number of chars(a-zA-Z) goes first

  2. Then there's exactly one space

  3. Exactly one char(a-zA-Z)

  4. Exactly one dot

  5. Exactly one char(a-zA-Z)

  6. Exactly one dot

I wrote this regex ^([a-zA-Z]*)+( {1})+([a-zA-Z]{1})+(\.)+([a-zA-Z]{1})+(\.), but it doesn't seem to work properly (the expression still allows n number of spaces, for example). How do I restrict it? {1} doesn't work.

Upvotes: 0

Views: 74

Answers (1)

Andronicus
Andronicus

Reputation: 26046

Try this:

^([a-zA-Z])+([ ]{1})([a-zA-Z]{1})([.])([a-zA-Z]{1})([.])

I've taken space and dots into class ([]). If you don't do this with dot, then it means any character. Alo pluses are redundant, they mean more than one character.

P.S.: @f1sh correctly notices, that having {1} doesn't change a thing, so the shorter form would be:

^([a-zA-Z])+([ ])([a-zA-Z])([.])([a-zA-Z])([.])

Upvotes: 2

Related Questions