Saturday, 24 December 2016

Find all href link value in HTML string posted in c# (Regex Part1)

08:08 Posted by Nikesh No comments
Let assume you have passed full html on form post to your action and you come with a need where you have to find all href link in that html string.

Assume you have got an string which contin links like 

 <html>
      <p>
          <a href="http://www.codesgonecrazy.com\">Crazy Codes </a>
      </p>
     <div>
         <a href="http://www.othersites.com\">Other sites links</a>
     </div>
</html>

To this in better way we can use regex i got in c#:

   Regex regex = new Regex("href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))", RegexOptions.IgnoreCase);


    Match i;

for (i = regex.Match(textcontrolvalue); i.Success; i = i.NextMatch())
    {
       //    Got groups of hrefs!!! ;

        foreach (Group gp in i.Groups)
        {
          
        string link = gp;

        } 
     }

Now further we can add each link in list from foreach.

enjoy!!




-------------------------------------------------

Regex For Phone And Zip checker in C#

 
-------------------------------------------------

In daily validation we always need right phone format and zip format checker.

Below regex will do this work very well!

Pass value of phone to IsValidPhone() and you will get result.


IsValidPhone(string phone)

private static bool IsPhoneValid(string phone)
{
    return Regex.IsMatch(phone, @"^\(?\d{3}\)?[\s\-]?\d{3}\-?\d{4}$");
}


this regex can be used with below types of formats:

(xxx)xxx-xxxx :- (987)654-3210
(xxx) xxx-xxxx :- (987) 654-3210
xxx-xxx-xxxx :- 987-654-3210
xxxxxxxxxx :- 9876543210


Now a regex for US ZIP checker:


private static bool IsZipValid(string zip)
{
    return Regex.IsMatch(zip, @"^\d{5}(\-\d{4})?$");
}


this will work with following formats:

xxxxx-xxxx: 98765-5678
xxxxx: 98765

            
 

0 comments:

Post a Comment