I'm working with C# and want to parse phone numbers from a string. I live in Switzerland, phone numbers can either have 10 digits like following pattern:
000 000 00 00
or can start with a +41
: +41 00 000 00 00
. I've written following regular expression:
var phone = new Regex(@"\b(\+41\s\d{2}|\d{3})\s?\d{3}\s?\d{2}\s?\d{2}\b");
This works perfectly fine with the first example, but the one with the "+41" doesn't match. I'm pretty sure there's a problem with the word boundary \b
and the following +
. When I remove the \b
at the start it finds a match with the +41
-example. My code:
var phone = new Regex(@"\b(\+41\s\d{2}|\d{3})\s?\d{3}\s?\d{2}\s?\d{2}\b");
var text = @"My first phonenumber is: +41 00 000 00 00. My second one is:
000 000 00 00. End.";
var phoneMatches = phone.Matches(text);
foreach(var match in phoneMatches)
{
Console.WriteLine(match);
}
Console.ReadKey();
Output: 000 000 00 00
.
Output without \b
:
+41 00 000 00 00
000 000 00 00
Any solutions?