Reputation: 42
I would like to remove telephone numbers from a string using C#. I have been experimenting using different variations of regex with little success.
I would like a solution that is quick to execute (sub 0.1s if possible) as it will be used extensively in a production environment.
This is the code that I have been testing.
var stringContainingPhoneNumber = "This is some random text, I would like £4.99 for this item, please call me on 07828123456 for further information.";
var numberReplace = new Regex(@"((\d){3}-1234567)|((\d){3}\-(\d){3}\-4567)|((\d){3}1234567)");
stringContainingPhoneNumber = numberReplace.Replace(stringContainingPhoneNumber, "[TELEPHONE REMOVED]");
Upvotes: 0
Views: 1213
Reputation: 3653
Assuming UK numbers, for example:
"This is some random text, I would like £4.99 for this item, please call me on 07828123456 for further information or send a fax through (020) 2341 0231 or on (01204) 54203."
This should get just the phone numbers:
[\d\s-\(\)]{10,}
Upvotes: 0
Reputation: 174834
Just change your regex to ,
var numberReplace = new Regex(@"((\d){3}-1234567)|((\d){3}\-(\d){3}\-4567)|((\d){3}1234567)|(\b(\d){5}123456\b)");
Your regex won't work because in the input string, phone number contains 11 digits but in your pattern , there are only 10 digits. An also it isn't ends with 123456
Upvotes: 0
Reputation: 353
This should work for your regex.
\d{11}[\s\d-]+
The number in the regex will match number sequences of that length in the string.
Upvotes: 0
Reputation: 871
You may want to use a phone formatting library to identify valid phone numbers. Than you can replace them with whatever you want. You may use
http://blog.appharbor.com/2012/02/03/net-phone-number-validation-with-google-libphonenumber
Upvotes: 1