How to read RegEx Captures in C#

前端 未结 3 919
耶瑟儿~
耶瑟儿~ 2020-11-28 15:18

I started a C# book and I decided to throw RegEx\'s into the mix to make the boring console exercises a little more interesting. What I want to do is ask a user for their ph

3条回答
  •  迷失自我
    2020-11-28 15:48

    string pattern = @"[(]?(\d{3})[)]?[ -.]?(\d{3})[ -.]?(\d{4})";
    
    System.Console.WriteLine("What is your phone number?");
    string phoneNumber = Console.ReadLine();
    
    while (!Regex.IsMatch(phoneNumber, pattern))
    {
        Console.WriteLine("Bad Input");
        phoneNumber = Console.ReadLine();
    }
    
    var match = Regex.Match(phoneNumber, pattern);
    if (match.Groups.Count == 4)
    {
        System.Console.WriteLine("Number matched : "+match.Groups[0].Value);
        System.Console.WriteLine(match.Groups[1].Value + "-" + match.Groups[2].Value + "-" + match.Groups[3].Value);
    }
    

提交回复
热议问题