C# 用空字符串替换非数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/262448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace non-numeric with empty string
提问by Matt Dawdy
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?
在我们的项目中快速添加需求。我们数据库中保存电话号码的字段设置为仅允许 10 个字符。因此,如果我通过“(913)-444-5555”或其他任何东西,是否有一种快速的方法可以通过某种特殊的替换函数来运行字符串,我可以向它传递一组字符以允许?
Regex?
正则表达式?
采纳答案by Joel Coehoorn
Definitely regex:
绝对正则表达式:
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, "");
}
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).
根据您的实际输入,您可能需要一些额外的逻辑来执行诸如去除前导 1(用于长距离)或任何尾随 x 或 X(用于扩展)的操作。
回答by Jon Norton
I'm sure there's a more efficient way to do it, but I would probably do this:
我确信有一种更有效的方法来做到这一点,但我可能会这样做:
string getTenDigitNumber(string input)
{
StringBuilder sb = new StringBuilder();
for(int i - 0; i < input.Length; i++)
{
int junk;
if(int.TryParse(input[i], ref junk))
sb.Append(input[i]);
}
return sb.ToString();
}
回答by CMS
You can do it easily with regex:
您可以使用正则表达式轻松完成:
string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"
回答by Wes Mason
Using the Regex methods in .NET you should be able to match any non-numeric digit using \D, like so:
使用 .NET 中的 Regex 方法,您应该能够使用 \D 匹配任何非数字数字,如下所示:
phoneNumber = Regex.Replace(phoneNumber, "\D", "");
回答by Charles Bretana
try this
尝试这个
public static string cleanPhone(string inVal)
{
char[] newPhon = new char[inVal.Length];
int i = 0;
foreach (char c in inVal)
if (c.CompareTo('0') > 0 && c.CompareTo('9') < 0)
newPhon[i++] = c;
return newPhon.ToString();
}
回答by Aaron
Here's the extension method way of doing it.
这是执行此操作的扩展方法方法。
public static class Extensions
{
public static string ToDigitsOnly(this string input)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(input, "");
}
}
回答by Usman Zafar
You don't need to use Regex.
您不需要使用正则表达式。
phone = new String(phone.Where(c => char.IsDigit(c)).ToArray())
回答by Michael Lang
How about an extension method that doesn't use regex.
不使用正则表达式的扩展方法怎么样。
If you do stick to one of the Regex options at least use RegexOptions.Compiled
in the static variable.
如果您确实坚持使用 Regex 选项之一,则至少RegexOptions.Compiled
在静态变量中使用。
public static string ToDigitsOnly(this string input)
{
return new String(input.Where(char.IsDigit).ToArray());
}
This builds on Usman Zafar's answer converted to a method group.
这建立在 Usman Zafar 的答案转换为方法组的基础上。
回答by Max-PC
for the best performance and lower memory consumption , try this:
为了获得最佳性能和更低的内存消耗,请尝试以下操作:
using System;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
public class Program
{
private static Regex digitsOnly = new Regex(@"[^\d]");
public static void Main()
{
Console.WriteLine("Init...");
string phone = "001-12-34-56-78-90";
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000000; i++)
{
DigitsOnly(phone);
}
sw.Stop();
Console.WriteLine("Time: " + sw.ElapsedMilliseconds);
var sw2 = new Stopwatch();
sw2.Start();
for (int i = 0; i < 1000000; i++)
{
DigitsOnlyRegex(phone);
}
sw2.Stop();
Console.WriteLine("Time: " + sw2.ElapsedMilliseconds);
Console.ReadLine();
}
public static string DigitsOnly(string phone, string replace = null)
{
if (replace == null) replace = "";
if (phone == null) return null;
var result = new StringBuilder(phone.Length);
foreach (char c in phone)
if (c >= '0' && c <= '9')
result.Append(c);
else
{
result.Append(replace);
}
return result.ToString();
}
public static string DigitsOnlyRegex(string phone)
{
return digitsOnly.Replace(phone, "");
}
}
The result in my computer is:
Init...
Time: 307
Time: 2178
在我的电脑中的结果是:
Init...
时间:307
时间:2178