Leonardo
Leonardo

Reputation: 11391

Regex to split string and Date

I'm trying to split a pattern such as John Doe 12/01/1950, John * Doe 12/01/1950, John 12/01/1950, 12/01/1950 John and 12/01/1950 John * Doe using C#. The expected Result is the date in one string and the rest in another...

Upvotes: 0

Views: 985

Answers (2)

Ulugbek Umirov
Ulugbek Umirov

Reputation: 12807

You can do like this:

string[] lines = new[] {
    "John Doe 12/01/1950",
    "John * Doe 12/01/1950",
    "John 12/01/1950",
    "12/01/1950 John",
    "12/01/1950 John * Doe" };
foreach (string line in lines)
{
    Match m = Regex.Match(line, @"(?<name1>.*?)\s?(?<date>\d\d/\d\d/\d{4})\s?(?<name2>.*)");
    string date = m.Groups["date"].Value;
    string name = m.Groups["name1"].Value + m.Groups["name2"].Value;
    Console.WriteLine("{0} - {1}", date, name);
}

Upvotes: 1

mareoraft
mareoraft

Reputation: 3902

Match a date with

(\d+/){2}\d+

That is, one or more digits, followed by a slash, repeat twice, followed by one or more digits. If you want to be specific about how many digits they put, you can use

\d\d/\d\d/\d\d\d\d

We can match the name by searching for word characters (\w)

(\w+ +\* +\w+)|(\w+ +\w+)|(\w+)

which means "word spaces star spaces word" or "word spaces word" or "word" respectively.

Upvotes: 2

Related Questions