Edit: I solving the following task, but I have some problems with it.
Task: Write a program that selects a correctly formatted phone number from the text and, if it matches a regular expression, lists the entire match with the regular expression separately, the country code separately, and the phone number separately. The corrects formats are: +xxx xxx xxx xxx, (xxx) xxx xxx xxx, xxx xxx xxx, xxxxxxxxx, +xxxxxxxxxxxx. I need this task #C .NET 4.7.2. Thanks for help.
I have this code:
using System.Linq;
using System.Text.RegularExpressions;
public class Program {
private static string MakeRegex(params string[] patterns) {
string SinglePattern(string pattern) => "(?:^" + string.Concat(Regex
.Split(pattern, "(x+)")
.Select(item => item.StartsWith('x')
? $"[0-9]{{{item.Length}}}"
: string.Concat(item.Select(c => Regex.Escape(c.ToString()))))) + "$)";
return string.Join("|", patterns.Select(pattern => SinglePattern(pattern)));
}
public static void Main() {
string Patterns = MakeRegex(
"+xxx xxx xxx xxx",
"(xxx) xxx xxx xxx",
"xxx xxx xxx",
"xxxxxxxxx",
"+xxxxxxxxxxxx"
);
string[] PhoneNumbers = new string[] {
"+420 000 111 222",
"(420) 000 111 222",
"111 000 222",
"000111222",
"+420000111222",
"000111",
"+(420) 000 111 222"
};
string numbers = string.Join(Environment.NewLine, PhoneNumbers
.Select(test => $"{test,20} : {(Regex.IsMatch(test, Patterns) ? "Matched" : "No")}"));
string[] ns = numbers.Split('\n');
foreach (var n in ns)
{
Console.WriteLine(n);
}
}
}