Csharp/CSharp Tutorial/Regular Expression/Regex Match

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Capture Collection

using System;
using System.Text.RegularExpressions;
    class Test
    {
        public static void Main()
        {
            string string1 = "04:03:27 abc 0.0.0.127 def";
            Regex theReg = new Regex(@"(?<time>(\d|\:)+)\s" +
                            @"(?<company>\S+)\s" +
                            @"(?<ip>(\d|\.)+)\s" +
                            @"(?<company>\S+)\s");
            MatchCollection theMatches = theReg.Matches(string1);
            foreach (Match theMatch in theMatches)
            {
                if (theMatch.Length != 0)
                {
                    Console.WriteLine("theMatch: {0}",theMatch.ToString());
                    Console.WriteLine("time: {0}",theMatch.Groups["time"]);
                    Console.WriteLine("ip: {0}",theMatch.Groups["ip"]);
                    Console.WriteLine("Company: {0}",theMatch.Groups["company"]);
                    foreach (Capture cap in theMatch.Groups["company"].Captures)
                    {
                        Console.WriteLine("cap: {0}", cap.ToString());
                    }
                }
            }
        }
    }

Get matched parts

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

Match index and value

using System;
using System.Text.RegularExpressions;
public class MainClass
{
    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])\." +
                         @"\k<part1>\." +
                         @"\k<part1>\." +
                         @"\k<part1>";
        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 );
            match = match.NextMatch();
        }
    }
}

Match words that contain any letters in the range "b" through "d"

using System;
using System.Text.RegularExpressions;
class MainClass {
  private static void DisplayMatches(string text,string regularExpressionString) {
    Console.WriteLine("using the following regular expression: " +regularExpressionString);
    MatchCollection myMatchCollection = Regex.Matches(text, regularExpressionString);
    foreach (Match myMatch in myMatchCollection) {
      Console.WriteLine(myMatch);
    }
  }
  public static void Main() {
    string text ="knife knock five";
    
    Console.WriteLine("Matching words that contain any letters in the range "b" through "d"");
    DisplayMatches(text, @"\S*[b-d]\S*");
  }
}
Matching words that contain any letters in the range "b" through "d"
using the following regular expression: \S*[b-d]\S*
knock

Match words that contain "k" or "f"

using System;
using System.Text.RegularExpressions;
class MainClass {
  private static void DisplayMatches(string text,string regularExpressionString) {
    Console.WriteLine("using the following regular expression: " +regularExpressionString);
    MatchCollection myMatchCollection = Regex.Matches(text, regularExpressionString);
    foreach (Match myMatch in myMatchCollection) {
      Console.WriteLine(myMatch);
    }
  }
  public static void Main() {
    string text ="knife knock five";
    
    Console.WriteLine("Matching words that contain "k" or "f"");
    DisplayMatches(text, @"\S*[kf]\S*");
  }
}
Matching words that contain "k" or "f"
using the following regular expression: \S*[kf]\S*
knife
knock
five

Match words that contain the pattern "ai"

using System;
using System.Text.RegularExpressions;
class MainClass {
  private static void DisplayMatches(string text,string regularExpressionString) {
    Console.WriteLine("using the following regular expression: " +regularExpressionString);
    MatchCollection myMatchCollection = Regex.Matches(text, regularExpressionString);
    foreach (Match myMatch in myMatchCollection) {
      Console.WriteLine(myMatch);
    }
  }
  public static void Main() {
    string text ="put curtain pertain perday";
    
    Console.WriteLine("Matching words that contain the pattern "ai"");
    DisplayMatches(text, @"\S*(ai)\S*");
  }
}
Matching words that contain the pattern "ai"
using the following regular expression: \S*(ai)\S*
curtain
pertain

Match words that contain the pattern "ai" or "ie"

using System;
using System.Text.RegularExpressions;
class MainClass {
  private static void DisplayMatches(string text,string regularExpressionString) {
    Console.WriteLine("using the following regular expression: " +regularExpressionString);
    MatchCollection myMatchCollection = Regex.Matches(text, regularExpressionString);
    foreach (Match myMatch in myMatchCollection) {
      Console.WriteLine(myMatch);
    }
  }
  public static void Main() {
    string text ="put curtain pertain peiu";
    
    Console.WriteLine("Matching words that contain the pattern "ai" or "ie"");
    DisplayMatches(text, @"\S*(ai|ie)\S*");
  }
}
Matching words that contain the pattern "ai" or "ie"
using the following regular expression: \S*(ai|ie)\S*
curtain
pertain

Match words that contain two consecutive identical characters

using System;
using System.Text.RegularExpressions;
class MainClass {
  private static void DisplayMatches(string text,string regularExpressionString) {
    Console.WriteLine("using the following regular expression: " +regularExpressionString);
    MatchCollection myMatchCollection = Regex.Matches(text, regularExpressionString);
    foreach (Match myMatch in myMatchCollection) {
      Console.WriteLine(myMatch);
    }
  }
  public static void Main() {
    string text ="Missisipli Kerrisdale she";
    
    Console.WriteLine("Matching words that that contain two consecutive identical characters");
    DisplayMatches(text, @"\S*(.)\1\S*");
  }
}
Matching words that that contain two consecutive identical characters
using the following regular expression: \S*(.)\1\S*
Missisipli
Kerrisdale

Match words that contain "u"

using System;
using System.Text.RegularExpressions;
class MainClass {
  private static void DisplayMatches(string text,string regularExpressionString) {
    Console.WriteLine("using the following regular expression: " +regularExpressionString);
    MatchCollection myMatchCollection = Regex.Matches(text, regularExpressionString);
    foreach (Match myMatch in myMatchCollection) {
      Console.WriteLine(myMatch);
    }
  }
  public static void Main() {
    string text ="put public private she";
    
    Console.WriteLine("Matching words that contain "u"");
    DisplayMatches(text, @"\S*u+\S*");
  }
}
Matching words that contain "u"
using the following regular expression: \S*u+\S*
put
public

Match words that start with "s"

using System;
using System.Text.RegularExpressions;
class MainClass {
  private static void DisplayMatches(string text,string regularExpressionString) {
    Console.WriteLine("using the following regular expression: " +regularExpressionString);
    MatchCollection myMatchCollection = Regex.Matches(text, regularExpressionString);
    foreach (Match myMatch in myMatchCollection) {
      Console.WriteLine(myMatch);
    }
  }
  public static void Main() {
    string text ="end main void static start she";
    
    Console.WriteLine("Matching words that start with "s"");
    DisplayMatches(text, @"\bs\S*");
  }
}
Matching words that start with "s"
using the following regular expression: \bs\S*
static
start
she

Match words that start with "s" and end with "e"

using System;
using System.Text.RegularExpressions;
class MainClass {
  private static void DisplayMatches(string text,string regularExpressionString) {
    Console.WriteLine("using the following regular expression: " +regularExpressionString);
    MatchCollection myMatchCollection = Regex.Matches(text, regularExpressionString);
    foreach (Match myMatch in myMatchCollection) {
      Console.WriteLine(myMatch);
    }
  }
  public static void Main() {
    string text ="end main void static start she";
    
    Console.WriteLine("Matching words that start with "s" and end with "e"");
    DisplayMatches(text, @"\bs\S*e\b");
  }
}
Matching words that start with "s" and end with "e"
using the following regular expression: \bs\S*e\b
she

Next Match

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
public class MainClass{
   public static void Main(){
        Regex r = new Regex(@"^\G\d+$\n?", RegexOptions.Multiline);
        Match m = r.Match("13\n38\n18\n5");
        do {
            Console.WriteLine("Match: " + m.Value);
        } while ((m = m.NextMatch()).Success);
   }
}
Match: 13
Match: 38
Match: 18
Match: 5

Use Regex to validate your input

using System;
using System.Text.RegularExpressions;
class MainClass
{
    public static void Main(string[] args)
    {
        string regex = "your regex"; 
        string input = "your input";
        
        Regex r = new Regex(regex);
        Console.WriteLine(r.IsMatch(input));
        
        //or Regex.IsMatch(input, regex);
    }
}
False

Using Match Collection

using System;
using System.Text.RegularExpressions;
    class Test
    {
        public static void Main()
        {
            string string1 = "This is a test string";
            Regex theReg = new Regex(@"(\S+)\s");
            MatchCollection theMatches = theReg.Matches(string1);
            foreach (Match theMatch in theMatches)
            {
                Console.WriteLine(theMatch.Length);
                if (theMatch.Length != 0)
                {
                    Console.WriteLine("theMatch: {0}",
                                  theMatch.ToString());
                }
            }
        }
    }