URL-Parser in C# (.NET): using System.Text.RegularExpressions

Reguläre Ausdrücke sind ein sehr mächtiges Instrument zur Stringverarbeitung.

Mächtig bezieht sich dabei auch auf die Schwierigkeit damit korrekte saubere Ausdrücke zu schreiben.

Ich arbeite gerade an einem kleinen Crawler und muss deshalb auch URLs parsen. Im Web bin ich auf ein schönes Beispiel dazu unter C# gestoßen.

public void TestParseURL()
{
   string url = "http://www.cambiaresearch.com"
      + "/Cambia3/snippets/csharp/regex/uri_regex.aspx?id=17#authority";

   string regexPattern = @"^(?<s1>(?<s0>[^:/?#]+):)?(?<a1>"
      + @"//(?<a0>[^/?#]*))?(?<p0>[^?#]*)"
      + @"(?<q1>?(?<q0>[^#]*))?"
      + @"(?<f1>#(?<f0>.*))?";

   Regex re = new Regex(regexPattern, RegexOptions.ExplicitCapture);
   Match m = re.Match(url);

   lblOutput.Text = "<b>URL: " + url + "</b><p>";
   lblOutput.Text +=
      m.Groups["s0"].Value + "  (Scheme without colon)<br>";
   lblOutput.Text +=
      m.Groups["s1"].Value + "  (Scheme with colon)<br>";
   lblOutput.Text +=
      m.Groups["a0"].Value + "  (Authority without //)<br>";
   lblOutput.Text +=
      m.Groups["a1"].Value + "  (Authority with //)<br>";
   lblOutput.Text +=
      m.Groups["p0"].Value + "  (Path)<br>";
   lblOutput.Text +=
      m.Groups["q0"].Value + "  (Query without ?)<br>";
   lblOutput.Text +=
      m.Groups["q1"].Value + "  (Query with ?)<br>";
   lblOutput.Text +=
      m.Groups["f0"].Value + "  (Fragment without #)<br>";
   lblOutput.Text +=
      m.Groups["f1"].Value + "  (Fragment with #)<br>";
}
Die Ausgabe sieht dann folgendermaßen aus:
URL: http://www.cambiaresearch.com/Cambia3/snippets/csharp/
      regex/uri_regex.aspx?id=17#authority

http (Scheme without colon)
http: (Scheme with colon)
www.cambiaresearch.com (Authority without //)
//www.cambiaresearch.com (Authority with //)
/Cambia3/snippets/csharp/regex/uri_regex.aspx (Path)
id=17 (Query without ?)
?id=17 (Query with ?)
authority (Fragment without #)
#authority (Fragment with #)

Der Code hat wunderbar funktioniert! Ich muss jetzt nur noch den Code weiter optimieren (die Performance ist noch grottenschlecht) und noch ein oder zwei Features einbauen.

Share this content: