0

Hi guys I have string <span class="lnk">Участники&nbsp;<span class="clgry">59728</span></span> I parse it

string population = Regex.Match(content, @"Участники&nbsp;<span class=""clgry"">(?<id>[^""]+?)</span>").Groups["id"].Value;
int j = 0;
if (!string.IsNullOrEmpty(population))
{
    log("[+] Группа: " + group + " Учасники: " + population + "\r\n");
    int population_int = Convert.ToInt32(population);
    if (population_int > 20000)
    {
        lock (accslocker)
        {
        StreamWriter file = new StreamWriter("opened.txt", true);
        file.Write(group + ":" + population + "\r\n");
        file.Close();
    }
    j++;
}

}

But when my string is ><span class="lnk">Участники&nbsp;<span class="clgry"></span></span> I receive an exaption "Input string was not in a correct format". How to avoid it?

2 Answers 2

2

Instead of Regex use a real html parser to parse htmls. (for ex, HtmlAgilityPack)

string html = @"<span class=""lnk"">Участники&nbsp;<span class=""clgry"">59728</span>";
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);

var list = doc.DocumentNode.SelectNodes("//span[@class='lnk']/span[@class='clgry']")
              .Select(x => new
              {
                  ParentText = x.ParentNode.FirstChild.InnerText,
                  Text = x.InnerText
              })
              .ToList();
Sign up to request clarification or add additional context in comments.

Comments

1

Trying to parse html content with regex is not a good decision. See this. Use Html Agliliy Pack instead.

var spans = doc.DocumentNode.Descendants("span")
               .Where(s => s.Attributes["class"].Value == "clgry")
               .Select(x => x.InnerText)
               .ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.