如何使用正则表达式在模式上找到多个匹配项

时间:2013-12-06 20:35:15

标签: c# regex

我需要在字符串中找到模式的所有匹配项并将它们分开,以便我可以列出它们。目前我可以找到第一场比赛,但想在同一个字符串中找到任何其他比赛? 我对c#没有多少经验,所以任何帮助都会很棒。

namespace StringSearch
{
class TestRegularExpressionValidation
{
static void Main()
{
    string[] numbers = 
{
    "123-555-0190", 
    "444-234-22450", 
    "690-555-0178", 
    "146-893-232",
    "146-555-0122",
    "4007-555-0111", 
    "407-55-0111",
    "a1b-Cd-EfgH",
    "a1b-Cd-Efgn",
    "UM2345678",
    "11/12/2013 4:10:06 PM              UM2345678                   UM2345678",
    "407-2-5555", 
};
    string sPattern = "[A-Za-z]{2}[0-9]{4}";


    foreach (string s in numbers)
    {
        System.Console.Write("{0,14}", s);
        Match m = Regex.Match(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        if (m.Success)
        {
            System.Console.WriteLine(" - valid");
        }
        else
        {
            System.Console.WriteLine(" - invalid");
        }


    }

    // Keep the console window open in debug mode.
    System.Console.WriteLine("Press any key to exit.");
    System.Console.ReadKey();
   }
  }
}

2 个答案:

答案 0 :(得分:3)

使用Regex.Matches

MatchCollection matches = Regex.Matches(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

这是您为多个匹配更新的代码。

namespace StringSearch
{
    using System.Text.RegularExpressions;

    class TestRegularExpressionValidation
    {
        static void Main()
        {
            string[] numbers = 
{
    "123-555-0190", 
    "444-234-22450", 
    "690-555-0178", 
    "146-893-232",
    "146-555-0122",
    "4007-555-0111", 
    "407-55-0111",
    "a1b-Cd-EfgH",
    "a1b-Cd-Efgn",
    "UM2345678",
    "11/12/2013 4:10:06 PM              UM2345678                   UM2345678",
    "407-2-5555", 
};
            string sPattern = "[A-Za-z]{2}[0-9]{4}";


            foreach (string s in numbers)
            {
                System.Console.Write("{0,14}", s);
                MatchCollection matches = Regex.Matches(s, sPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                foreach (var match in matches)
                {
                    System.Console.WriteLine("{0} - valid", match.ToString());
                }
            }

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
        }
    }
}

答案 1 :(得分:0)

不是答案......但......

你应该把你的"按任意键退出"代码在某种条件下。

我更喜欢这种方法,因为无论附加什么调试器(例如VS,WinDbg等),它都可以工作,无论选择什么构建配置,在不在调试器下运行时自动关闭

if (Debugger.IsAttached()) {
    System.Console.WriteLine("Press any key to exit.");
    System.Console.ReadKey();
}

虽然这也是可行的,

#If DEBUG
    System.Console.WriteLine("Press any key to exit.");
    System.Console.ReadKey();
#EndIf