Like taking multiple groups in a Regex?

Asked

Viewed 483 times

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 take every "player" I could find and put in a list box, but I can’t, I’m learning to program now.

2 answers

6


As an alternative to Filipe’s solution, here’s something else for you to learn.

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

As for 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 Express.

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

5

Do it this way:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.