|
Dit artikel is gepubliceerd op zondag 31 juli 2011 op vbvoorbeelden, bezoek de website voor een recente versie van dit artikel of andere artikels.
Verschillende alternatieven kan men scheiden met een vertical bar ( | ).
Belangrijk hier is dat je weet dat deze operator de laagste prioriteit heeft. Visual Basic 2010 Broncode Imports System.Text.RegularExpressions Class Example Public Shared Sub Main() Dim input As String input = "abcdefghi" Print(input, "abc|ghi") Print(input, "abc|ghi|e") input = "this is a test bis" Print(input, "\bthis|is\b") Print(input, "\b(this|is)\b") Print(input, "\bis|this\b") Console.ReadLine() End Sub Public Shared Sub Print( ByVal input As String, ByVal pattern As String) Dim r As Regex = New Regex(pattern) Dim m As Match = r.Match(input) If m.Success Then Do Console.WriteLine( """" & input & """ has" & _ " match """ & m.Value & """ " & _ "at index " & m.Index.ToString() & _ " for pattern """ & pattern & """") m = m.NextMatch() Loop While m.Success Else Console.Write( """" & input & """ has no match" & _ " for pattern """ & pattern & """") End If End SubEnd ClassDownload Visual Basic 2010 Broncode Download Visual C# Sourcecode
Console Application Output "abcdefghi" has match "abc" at index 0 for pattern "abc|ghi"
"abcdefghi" has match "ghi" at index 6 for pattern "abc|ghi"
"abcdefghi" has match "abc" at index 0 for pattern "abc|ghi|e"
"abcdefghi" has match "e" at index 4 for pattern "abc|ghi|e"
"abcdefghi" has match "ghi" at index 6 for pattern "abc|ghi|e"
"this is a test bis" has match "this" at index 0 for pattern "\bthis|is\b"
"this is a test bis" has match "is" at index 5 for pattern "\bthis|is\b"
"this is a test bis" has match "is" at index 16 for pattern "\bthis|is\b"
"this is a test bis" has match "this" at index 0 for pattern "\b(this|is)\b"
"this is a test bis" has match "is" at index 5 for pattern "\b(this|is)\b"
"this is a test bis" has match "this" at index 0 for pattern "\bis|this\b"
"this is a test bis" has match "is" at index 5 for pattern "\bis|this\b" Bemerk hoe \b(this|is)\b en \bthis|is\b een ander resultaat opleveren.
Het eerste pattern zal zoeken naar de woorden ( tussen word boundaries \b ) "this" en "is". Het tweede pattern zoekt naar de tekst "this" voorafgegaan door een word boundary \b en naar de tekst "is" gevolgd door een word boundary \b. Hierdoor levert het laatste pattern ook de match "is" uit het woord "bis" op.
Merk ook op hoe het eerste pattern geen match "is" oplevert op index 2, daar staat nogthans de tekst "is" gevolgd door een word boundary \b. Maar omdat de regex engine "eager" is, is de cursor in de inputtekst na het vinden van de eerste match "this" geplaatst op het eerste karakter ( de spatie ) na "this".
Alternations worden ook wel "set unions" genoemd.
Dit artikel is gepubliceerd op zondag 31 juli 2011 op vbvoorbeelden, bezoek de website voor een recente versie van dit artikel of andere artikels.
|