XML technologies / Regular expressions / .NET / Helper functions
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Besides the functions in the previous section (Static convenience functions), other static helpers are available:
Regex.Escape(String)
Regex.Escape(...) takes a string and returns a copy with all regex metacharacters escaped. The result can be used as a literal in a regex.
For example, if a user enters a string Suchwort, ensure it contains no active metacharacters before including it in a regex:
Dim BenutzerRegex as Regex = New Regex("^" & Regex.Escape(Suchwort) & "$", _
RegexOptions.IgnoreCase)This lets users enter characters normally interpreted as metacharacters. If Suchwort were the string ‘:-)’, it would normally throw exception ArgumentException (see Catching exceptions).
Regex.Unescape(String)
This unusual function takes a string and returns one in which some backslash sequences have been interpreted and other backslashes removed. For example, ‘\:\-\)’ becomes ‘:-)’.
Character escape sequences are interpreted. If the argument contains ‘\n’, the result contains a real newline. Sequence ‘\u1234’ becomes the corresponding Unicode character. All character abbreviations in table Overview of .NET regex constructs are interpreted.
I see no useful regex application for Regex.Unescape, but it is handy for string manipulation.
Match.Empty
This function returns a Match object representing failure. It can initialize a Match object that may later receive data but will always be inspected. For example:
Dim SubjMatch as Match = Match.Empty 'Initialisieren für den Fall, dass in der Schleife
... 'nichts gefunden wird.
Dim Zeile as String
For Each Zeile in EmailKopfzeilen
'Wenn wir eine »Subject:«-Zeile haben, werden die Trefferdaten für später abgelegt ...
Dim ZeilenMatch as Match = Regex.Match(Zeile, "^Subject:\s*(.*)", _
RegexOptions.IgnoreCase)
If ZeilenMatch.Success
SubjMatch = ZeilenMatch
End If
...
Next
If SubjMatch.Success
Console.WriteLine(SubjMatch.Result("Betreff: $1"))
Else
Console.WriteLine("Kein Betreff!")
End IfIf string array EmailKopfzeilen contains no “Subject:” line, or no lines at all, object SubjMatch never receives match data. Inspecting it after the loop would fail unless it had first been initialized with Match.Empty.
Regex.CompileToAssembly(...)
This function saves a Regex object in an assembly; see Regex assemblies.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln