Get matched parts : Regex Match « Regular Expression « C# / CSharp Tutorial






using System;
using System.Text.RegularExpressions;

public class EntryPoint
{
    static void Main( string[] args ) {
        // Create regex to search for IP address pattern.
        string pattern = @"(?<part1>[01]?\d\d?|2[0-4]\d|25[0-5])\." +
                         @"(?<part2>[01]?\d\d?|2[0-4]\d|25[0-5])\." +
                         @"(?<part3>[01]?\d\d?|2[0-4]\d|25[0-5])\." +
                         @"(?<part4>[01]?\d\d?|2[0-4]\d|25[0-5])";
        Regex regex = new Regex( pattern );
        Match match = regex.Match( "192.168.169.1" );
        while( match.Success ) {
            Console.WriteLine( "IP Address found at {0} with " +
                               "value of {1}",
                               match.Index,
                               match.Value );
            Console.WriteLine( "Groups are:" );
            Console.WriteLine( "\tPart 1: {0}",
                               match.Groups["part1"] );
            Console.WriteLine( "\tPart 2: {0}",
                               match.Groups["part2"] );
            Console.WriteLine( "\tPart 3: {0}",
                               match.Groups["part3"] );
            Console.WriteLine( "\tPart 4: {0}",
                               match.Groups["part4"] );

            match = match.NextMatch();
        }
        
    }
}
IP Address found at 0 with value of 192.168.169.1
Groups are:
        Part 1: 192
        Part 2: 168
        Part 3: 169
        Part 4: 1








17.6.Regex Match
17.6.1.Match words that start with 's'
17.6.2.Match words that start with 's' and end with 'e'
17.6.3.Match words that contain two consecutive identical characters
17.6.4.Match words that contain 'u'
17.6.5.Match words that contain the pattern 'ai'
17.6.6.Match words that contain the pattern 'ai' or 'ie'
17.6.7.Match words that contain 'k' or 'f'
17.6.8.Match words that contain any letters in the range 'b' through 'd'
17.6.9.Use Regex to validate your input
17.6.10.Get matched parts
17.6.11.Match index and value
17.6.12.Next Match
17.6.13.Using Match Collection
17.6.14.Capture Collection
17.6.15.\s Match a white-space character.
17.6.16.[A-Z] Match any uppercase character from A to Z.
17.6.17.\w* Match zero or more word characters.
17.6.18.\b Match a word boundary.
17.6.19.th Match the literal characters "th".
17.6.20.[^o] Match any character that is not an "o".
17.6.21.\w+ Match one or more word characters.
17.6.22.Strip HTML start and end tags from each string if they are present