How to get multiple groups in a Regex?

7
    public string site = "http://www.tibia.com/community/?subtopic=worlds&world=Aurera";
    private Regex nomedochar = new Regex("subtopic=characters&name=(?<player>.*?)\" >");
    public string nomedochar2 = "";
    public Thread t;
    public List<string> player = new List<string>();

    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        this.nomedochar2 = new StreamReader(WebRequest.Create(site).GetResponse().GetResponseStream()).ReadToEnd();        
        Match math = this.nomedochar.Match(this.nomedochar2);

        this.player.Add(math.Groups["player"].Value);
        this.t = new Thread(Novathread);
        this.t.Start();
    }
    public void Novathread()
    {    
       for (int i = 0; i < 100; i++);
    }

I wanted him to get all the "player" he could find and put it in a list box, but I can not, I'm learning to program now.

    
asked by anonymous 20.04.2014 / 07:33

2 answers

6

As an alternative to Philip's solution here is something else to learn.

Your implementation blocks the UI when you're getting page content, which is not a good user experience. With .NET Framework 4.5 and C# 5.0 it has become much easier asynchronous programming, so you can take advantage of it.

As for the regular expression, instead of capturing a pattern, in this case, one can capture what is surrounded by patterns. To test and develop your regular expressions, I recommend the Expresso .

private async void button1_Click(object sender, EventArgs e)
{
    var players = await GetPlayersAsync("http://www.tibia.com/community/?subtopic=worlds&world=Aurera");

    this.listBox1.Items.AddRange(players);
}

private async Task<string[]> GetPlayersAsync(string url)
{
    var text = await (new HttpClient()).GetStringAsync(url);

    var regex = new Regex("(?<=\?subtopic\=characters&name\=)[^\"]*(?=\")");

    var matches = regex.Matches(text);

    return (from match in matches.Cast<Match>()
            select match.Value.Replace('+', ' ')).ToArray().Dump();;
}
    
20.04.2014 / 20:37
5

Do as follows:

this.nomedochar2 = new StreamReader(WebRequest.Create(site).GetResponse().GetResponseStream()).ReadToEnd();        
MatchCollection matches = nomedochar.Matches(nomedochar2);

this.player = matches.Cast<Match>().Select(match => match.Groups["player"].Value.Replace("+", " ")).ToList();
foreach (var item in player)
{
    listBox1.Add(item);
}
    
20.04.2014 / 08:19