正则表达式只匹配最后一次匹配.NET

时间:2018-04-05 16:31:31

标签: c# .net regex

这可能是重复的,但我太密集了,无法完成这项工作。我正在尝试学习捕获组等,但我不能使这个工作,我得到正确的匹配,但只有最后一个数字匹配。

    class Program
   {

    static void Main(string[] args)
    {
        string testTxt = "sadsadas168.asdsad";
        string asdf = "wrongwrong";
        string abc = "abc.png";
        string bsdf = "100";
        string lolol = "155abx.text";
        string another = "sasd199.ong100";

        TryMatch(testTxt);
        TryMatch(asdf);
        TryMatch(abc);
        TryMatch(bsdf);
        TryMatch(lolol);
        TryMatch(another);

        Console.ReadLine();

    }

    private static void TryMatch(string txt)
    {
        var rgx = new Regex(@"\w*(?<t>\d+)\w*\..*");
        var m = rgx.Match(txt);

        if (m.Success)
        {
            int mainID = int.Parse(m.Groups["t"].Value);
            Console.WriteLine(m.Groups["t"].Value);
        }
        else
        {
            Console.WriteLine("Did not match " + txt);
        }
    }
}

0 个答案:

没有答案