-2

I have a task to write a regex for a valid name. It has to consist two words, each word starts with capital letter, afterwards contains only lowercase letters, should be at least two letters long and the words are separated by a space.

string input = "Stephen King, Bruce hatow, eddie Lee, AShley Greene, Test Testov, Ann   Grey";

        string pattern = @"^\b[A-Z][a-z]{1,}\s\b[A-Z][a-z]{1,}$";

        MatchCollection output = Regex.Matches(input, pattern);

        foreach (Match item in output)
        {
            Console.Write(item);
        }

My pattern matches only if the string has one name. e.g. string input = "Stephen King". Is there a way to do it with string or I should use List of strings and check each one of them

max plant
  • 25
  • 2
  • 1
    See https://stackoverflow.com/questions/6908725/what-do-and-mean-in-a-regular-expression/6908745#6908745 and https://stackoverflow.com/questions/6664151/difference-between-b-and-b-in-regex/6664167#6664167 – The fourth bird Jul 04 '20 at 10:20

1 Answers1

0

Try removing the starting and ending anchors ^ and $. Instead, replace them with word boundaries, allowing for a first/last name match to occur anywhere in the input string:

string input = "Stephen King, Bruce hatow, eddie Lee, AShley Greene, Test Testov, Ann   Grey";
string pattern = @"\b[A-Z][a-z]{1,}\s[A-Z][a-z]{1,}\b";
MatchCollection output = Regex.Matches(input, pattern);
foreach (Match item in output)
{
    Console.Write(item + "\n");
}

This prints:

Stephen King
Test Testov
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360