using System.Text.RegularExpressions;
private static string MakeRegex(params string[] patterns) {
static string SinglePattern(string pattern) => "(?:" + string.Concat(Regex
.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 phonePattern = MakeRegex(
string[] tests = new string[] {
string report = string.Join(Environment.NewLine, tests
.Select(test => $"{test,20} : {(Regex.IsMatch(test, phonePattern) ? "Matched" : "No")}"));
Console.WriteLine(report);
Console.WriteLine("Parsed Demo");
@"This is the sample text with phones: +420 000 111 222,
and (420) 555 789 567 or 123456789 and some numbers 123 or 78.";
.Matches(text, phonePattern)
.Select(m => string.Concat(m.Value.Where(c => c >= '0' && c <= '9')))
country = phone.Length > 9 ? phone.Substring(0, 3) : "",
number = phone.Length > 9 ? phone.Substring(3) : phone
Console.WriteLine(string.Join(Environment.NewLine, parsed));