CSharp · Console
using System;
using System.Linq;
using System.Text.RegularExpressions;
public class Program {
private static string MakeRegex(params string[] patterns) {
static 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 phonePattern = MakeRegex(
"+xxx xxx xxx xxx",
"(xxx) xxx xxx xxx",
"xxx xxx xxx",
"xxxxxxxxx",
"+xxxxxxxxxxxx"
);
string[] tests = new string[] {
//TODO: Add more tests here
"+123 456 789 777",
"(123) 456 789 444",
"123 456 789",
"123456789",
"+123456789567",
"12345678",
"1234567899",
"1234 56 789",
};
string report = string.Join(Environment.NewLine, tests
.Select(test => $"{test,20} : {(Regex.IsMatch(test, phonePattern) ? "Matched" : "No")}"));
Console.WriteLine(report);
Console.WriteLine();
Console.WriteLine("Parsed Demo");
Console.WriteLine();
string text =
@"This is the sample text with phones: +420 000 111 222,
and (420) 555 789 567 or 123456789 and some numbers 123 or 78.";
var parsed = Regex
.Matches(text, phonePattern)
.Cast<Match>()
.Select(m => string.Concat(m.Value.Where(c => c >= '0' && c <= '9')))
.Select(phone => new {
country = phone.Length > 9 ? phone.Substring(0, 3) : "",
number = phone.Length > 9 ? phone.Substring(3) : phone
});
Console.WriteLine(string.Join(Environment.NewLine, parsed));
}
}