Ajax...">

How to extract useful regular expression data in C #

I have a line that

<a href="/KB/ajax/" id="ctl00_MC_TCRp_ctl01_TSRp_ctl01_TSNL">Ajax</a>

now I want to get / KB / ajax / and Ajax with a Regex class in C #.

Can anybody help me?

Thank you so much

Greetings

+3
source share
2 answers
string url = "<a href=\"/KB/ajax/\" id=\"ctl00_MC_TCRp_ctl01_TSRp_ctl01_TSNL\">Ajax</a>";

Regex finder = new Regex("href=\"([^\"]*)\"");
string first = finder.Match(url).Groups[1].Value;

finder = new Regex(">([^<]*)<");
string second = finder.Match(url).Groups[1].Value;
+2
source

The following regular expression also allows you to use tags inside text enclosed in <a>...</a>:

<\s*a\b[^>] href\s*=\s*['"]([^"']*)['"][^>]*>((?:.(?!</a))*.)</a

C # .NET Code Example:

using System;
using System.Text.RegularExpressions;
namespace myapp
{
  class Class1
    {
      static void Main(string[] args)
        {
          String sourcestring = "source string to match with pattern";
          Regex re = new Regex(@"\<\s*a\b[^\>]+href\s*=\s*['""]([^""']*)['""][^\>]*\>((?:.(?!<\/a))*.)\<\/a");
          MatchCollection mc = re.Matches(sourcestring);
          int mIdx=0;
          foreach (Match m in mc)
           {
            for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
              {
                Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
              }
            mIdx++;
          }
        }
    }
}

$ corresponds to an array:

(
    [0] => Array
        (
            [0] => <a href="/KB/ajax/" id="ctl00_MC_TCRp_ctl01_TSRp_ctl01_TSNL">Aj<b>a</b>x</a
        )

    [1] => Array
        (
            [0] => /KB/ajax/
        )

    [2] => Array
        (
            [0] => Aj<b>a</b>x
        )

)
0
source

Source: https://habr.com/ru/post/1790485/


All Articles