问题描述
快速添加在我们的项目需求。在我们的数据库来保存电话号码字段设置为仅允许10个字符。所以,如果我得到传承(913)-444-5555或其他任何东西,是有一个快速的方法来运行通过某种特殊的字符串替换功能,我可以通过它的字符集,允许?
Quick add on requirement in our project. A field in our DB to hold a phone number is set to only allow 10 characters. So, if I get passed "(913)-444-5555" or anything else, is there a quick way to run a string through some kind of special replace function that I can pass it a set of characters to allow?
正则表达式?
推荐答案
绝对正则表达式:
string CleanPhone(string phone)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(phone, "");
}
或类中,以避免重新创建正则表达式的所有时间:
or within a class to avoid re-creating the regex all the time:
private static Regex digitsOnly = new Regex(@"[^\d]");
public static string CleanPhone(string phone)
{
return digitsOnly.Replace(phone, "");
}
根据您的真实世界的输入,您可能需要一些额外的逻辑在那里做的事情一样去掉领先1的(长途)或任何尾随的X或X(分机)。
Depending on your real-world inputs, you may want some additional logic there to do things like strip out leading 1's (for long distance) or anything trailing an x or X (for extensions).
这篇关于更换非数字与空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!