Chamov
Chamov

Reputation: 179

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?

Upvotes: 0

Views: 479

Answers (1)

MarZab
MarZab

Reputation: 2623

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);
}

Upvotes: 1

Related Questions