Get Dom Element By Attribute using regex from html string - CSharp System

CSharp examples for System:String HTML

Description

Get Dom Element By Attribute using regex from html string

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Net;
using System.IO;//from w ww. ja  va 2 s.com
using System.Collections.Generic;
using System;

public class Main{

        public static List<string> GetDomElemByAttr(string source, string tagName, string tagValue)
        {
            var matchList = new List<string>();
            string regStr =
                string.Format(
                    @"<(?<HtmlTag>[\w]+)[^>]*\s{0}[\s]*?=[\s]*?(?<Quote>[""']?){1}(?(Quote)\k<Quote>)[""']?[^>]*>((?<Nested><\k<HtmlTag>[^>]*>)|</\k<HtmlTag>>(?<-Nested>)|[\s\S]*?)*</\k<HtmlTag>>",
                    tagName.ToLower(), tagValue);
            try
            {
                var regex = new Regex(regStr, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                var matches = regex.Matches(source);
                foreach (Match match in matches)
                {
                    matchList.Add(match.Value);
                }
            }
            catch (Exception ex)
            {
                matchList.Add(ex.Message);
            }
            return matchList;
        }
}

Related Tutorials