Quantcast Regex matching and naming groups in Net

Regex matching and naming groups in Net

by Neon Quach 23. October 2010 16:10

Playing with Regular Expression is very interesting, by placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together.

Let say you have a string which holds teams name and  time of the match. Here is you string: “12:45 Manchester vs Arsenal”, and now you will split this string to 2 groups, one of them is time and the team name.

I just created C# and VB.NET console application for the demo purpose

using System;
using System.Text.RegularExpressions;

namespace CS
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "12:45 Manchester vs Arsenal";
            string pattern = @"(?<time>\d{2}:\d{2})[\s](?<teams>.*)";
            Match m = Regex.Match(text, pattern);
            if (m.Success)
            {
                string time = m.Groups["time"].Value;
                string teams = m.Groups["teams"].Value;
                Console.WriteLine(time);
                Console.WriteLine(teams);
            }
            Console.Read();
        }
    }
}

VB.NET:
Snippet

Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
        Dim text As String = "12:45 Manchester vs Arsenal"
        Dim pattern As String = "(?<time>\d{2}:\d{2})[\s](?<teams>.*)"
        Dim m As Match = Regex.Match(text, pattern)
        If m.Success Then
            Dim time = m.Groups("time").Value
            Dim teams = m.Groups("teams").Value
            Console.WriteLine(time)
            Console.WriteLine(teams)
        End If
        Console.ReadLine()
    End Sub

End Module

In the patten: (?<time>\d{2}:\d{2})[\s](?<teams>.*), we have 2 groups: (?<time>\d{2}:\d{2}) and (?<teams>.*), time and teams are name of group which goes inside the angle brackets < > preceded by a question mark.

\d{2}:\d{2}:
This pattern matchs with (2 digits, colon and 2 digits.
[\s](?<teams>.*):
It matches with space + any characters.

Run application you will see the result:


12:45

Manchester vs Arsenal

ReguarExpressionGroup.rar (65.56 kb)

Have fun

Tags: , ,


Categories: regular expression | c# | vb.net

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Powered by BlogEngine.NET 2.5.0.5 - Eco Theme by n3o Web Designers