私たちのプロジェクトの要件をすばやく追加します。電話番号を保持する DB のフィールドは、10 文字のみを許可するように設定されています。したがって、「(913)-444-5555」などを渡された場合、許可する一連の文字を渡すことができる特別な置換関数を使用して文字列を実行する簡単な方法はありますか?
正規表現?
私たちのプロジェクトの要件をすばやく追加します。電話番号を保持する DB のフィールドは、10 文字のみを許可するように設定されています。したがって、「(913)-444-5555」などを渡された場合、許可する一連の文字を渡すことができる特別な置換関数を使用して文字列を実行する簡単な方法はありますか?
正規表現?
間違いなく正規表現:
string CleanPhone(string phone)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(phone, "");
}
またはクラス内で、常に正規表現を再作成しないようにします。
private static Regex digitsOnly = new Regex(@"[^\d]");
public static string CleanPhone(string phone)
{
return digitsOnly.Replace(phone, "");
}
実世界の入力によっては、先頭の 1 (長距離の場合) や末尾の x または X (拡張の場合) を取り除くなどの追加のロジックが必要になる場合があります。
正規表現で簡単に行うことができます:
string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"
これを行う拡張メソッドの方法は次のとおりです。
public static class Extensions
{
public static string ToDigitsOnly(this string input)
{
Regex digitsOnly = new Regex(@"[^\d]");
return digitsOnly.Replace(input, "");
}
}
.NET で Regex メソッドを使用すると、次のように \D を使用して数値以外の数字と一致させることができます。
phoneNumber = Regex.Replace(phoneNumber, "\\D", String.Empty);
最高のパフォーマンスとより低いメモリ消費量のために、これを試してください:
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, "");
}
}
私のコンピューターでの結果は次のとおりです
。Init...
Time: 307
Time: 2178
もっと効率的な方法があると思いますが、おそらくこれを行うでしょう:
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();
}
これを試して
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();
}