Regex.Match Method

 

Regex.Match 有六種多載方法

 

一、Match(string input)

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "she his him";
        string pattern = @"\bh\w+\b";

        Regex regex = new Regex(pattern);
        Match match = regex.Match(input);

        Console.WriteLine(match.Value);
    }
}

結果為

 

二、Match(string input, int beginning)

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "0123456789";
        string pattern = @"\d";

        Regex regex = new Regex(pattern);
        Match match = regex.Match(input, 5);

        Console.WriteLine(match.Value);
    }
}

結果為

說明:

從位置從 0 算起到第 5 個位置,開始找尋。

 

三、Match(string input, int beginning, int length)

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "0123456789";
        string pattern = @"\d{3}";

        Regex regex = new Regex(pattern);
        Match match = regex.Match(input, 5, 4);

        Console.WriteLine(match.Value);
    }
}

結果為

說明:

從位置從 0 算起到第 5 個位置,開始找尋,找尋範圍為 4 個長度。

 

四、Match(string input, string pattern)

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "she his him";
        string pattern = @"\bh\w+\b";

        Match match = Regex.Match(input, pattern);

        Console.WriteLine(match.Value);
    }
}

結果為

 

五、Match(string input, string pattern, RegexOptions options)

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = "she His him";
        string pattern = @"\bh\w+\b";

        Match match = Regex.Match(input, pattern, RegexOptions.IgnoreCase);

        Console.WriteLine(match.Value);
    }
}

結果為

 

六、Match(string input, string pattern, RegexOptions options, TimeSpan matchTimeout)

Searches the input string for the first occurrence of the specified regular expression, using the specified matching options and time-out interval.