-2

I want to create a Regular Expression for First Name and Last Name Only with only 2 words with only 1 Space.

Currently my regular expression is here : https://regex101.com/r/WigXOo/1

I have tried the below regular expression:

[A-Z][a-z]+(\s|,)[A-Z][a-z]{1,19}

it is validating correctly :

Sunil Kumar (Correct)

But it is allowing third Name like: Sunil Kumar 123 (Correct)

I want my results like below :

Correct Output:

Sunil Kumar (correct)

InCorrect Output:

  • Sunil Kumar 123 (incorrect) (I want only first and second name)

  • SUnil Kumar (incorrect) (needed only 1 letter from 1st name and 2nd letter from second name would be capital)

  • Sunil Kumar (incorrect) (needed only single space between 1st and 2nd name) (there are 2 spaces between first name and second name)

Please help.

Sunil Kumar
  • 3,142
  • 1
  • 19
  • 33
  • What is your problem you said Sunil Kumar (correct) and Sunil Kumar (incorrect) but there is no difference between them. –  Nov 17 '16 at 10:38
  • 4
    Obligatory [Falsehoods Programmers Believe About Names](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/). Also, go read a regex tutorial. You need start and end anchors. Please read [ask] and share your research. "What have you tried" does not mean "Show the code that does not work", it means "Show what you tried getting that code to work". – CodeCaster Nov 17 '16 at 10:38
  • 1
    there are 2 spaces between first name and last name I have mentioned that. – Sunil Kumar Nov 17 '16 at 10:38
  • It doesn't match the 2 spaces version anyway – TheLethalCoder Nov 17 '16 at 10:39

1 Answers1

2

You can add anchors to your expression to match the whole input i.e. ^ and $ so your expression would become:

^[A-Z][a-z]+(\s|,)[A-Z][a-z]{1,19}$
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69