' This code example demonstrates using the balancing group definition feature of
' regular expressions to match balanced left angle bracket (<) and right angle
' bracket (>) characters in a string.
Imports System
Imports System.Text.RegularExpressions
Class Sample
Public Shared Sub Main()
'
' The following expression matches all balanced left and right angle brackets(<>).
' The expression:
' 1) Matches and discards zero or more non-angle bracket characters.
' 2) Matches zero or more of:
' 2a) One or more of:
' 2a1) A group named "Open" that matches a left angle bracket, followed by zero
' or more non-angle bracket characters.
' "Open" essentially counts the number of left angle brackets.
' 2b) One or more of:
' 2b1) A balancing group named "Close" that matches a right angle bracket,
' followed by zero or more non-angle bracket characters.
' "Close" essentially counts the number of right angle brackets.
' 3) If the "Open" group contains an unaccounted for left angle bracket, the
' entire regular expression fails.
'
Dim pattern As String = "^[^<>]*" & _
"(" + "((?'Open'<)[^<>]*)+" & _
"((?'Close-Open'>)[^<>]*)+" + ")*" & _
"(?(Open)(?!))$"
Dim input As String = "<abc><mno<xyz>>"
'
Dim m As Match = Regex.Match(input, pattern)
If m.Success = True Then
Console.WriteLine("Input: ""{0}"" " & vbCrLf & "Match: ""{1}""", _
input, m)
Else
Console.WriteLine("Match failed.")
End If
End Sub 'Main
End Class 'Sample
'This code example produces the following results:
'
'Input: "<abc><mno<xyz>>"
'Match: "<abc><mno<xyz>>"
'
// This code example demonstrates using the balancing group definition feature of
// regular expressions to match balanced left angle bracket (<) and right angle
// bracket (>) characters in a string.
using System;
using System.Text.RegularExpressions;
class Sample
{
public static void Main()
{
/*
The following expression matches all balanced left and right angle brackets(<>).
The expression:
1) Matches and discards zero or more non-angle bracket characters.
2) Matches zero or more of:
2a) One or more of:
2a1) A group named "Open" that matches a left angle bracket, followed by zero
or more non-angle bracket characters.
"Open" essentially counts the number of left angle brackets.
2b) One or more of:
2b1) A balancing group named "Close" that matches a right angle bracket,
followed by zero or more non-angle bracket characters.
"Close" essentially counts the number of right angle brackets.
3) If the "Open" group contains an unaccounted for left angle bracket, the
entire regular expression fails.
*/
string pattern = "^[^<>]*" +
"(" +
"((?'Open'<)[^<>]*)+" +
"((?'Close-Open'>)[^<>]*)+" +
")*" +
"(?(Open)(?!))$";
string input = "<abc><mno<xyz>>";
//
Match m = Regex.Match(input, pattern);
if (m.Success == true)
Console.WriteLine("Input: \"{0}\" \nMatch: \"{1}\"", input, m);
else
Console.WriteLine("Match failed.");
}
}
/*
This code example produces the following results:
Input: "<abc><mno<xyz>>"
Match: "<abc><mno<xyz>>"
*/