Search code examples
c#regexmultiple-matches

C# Regex is matching too much


My regex should work like this: https://regex101.com/r/dY9jI4/1
It should Match only Nicknames (personaname).

My C# code looks like this:

string pattern = @"personaname"":\s+""([^""]+)""";
string users = webClient.DownloadString("http://pastebin.com/raw/cDHTXXD3");
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(users);
foreach (Match match in matches)
{
    Console.WriteLine(match.Value);
}

But in VS15 my regex in matching my whole pattern, so console output looks like:

personaname": "Tom"
personaname": "Emily"

Is something wrong with my pattern? How can I fix it?


Solution

  • So while the actual answer would be to just parse this JSON and get the data, your problem is in Match, you need match.Groups[1].Value to get that unnamed group.

    string pattern = @"personaname"":\s+""(?<name>[^""]+)""";
    string users = webClient.DownloadString("http://pastebin.com/raw/cDHTXXD3");
    Regex regex = new Regex(pattern);
    MatchCollection matches = regex.Matches(users);
    foreach (Match match in matches)
    {
        Console.WriteLine(match.Groups["name"].Value);
    }