非数値を空の文字列に置き換えます
-
06-07-2019 - |
質問
プロジェクトのクイック追加要件。電話番号を保持する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"
正規表現を使用する必要はありません。
phone = new String(phone.Where(c => char.IsDigit(c)).ToArray())
これを行う拡張メソッドの方法を次に示します。
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", "");
正規表現を使用しない拡張メソッドはどうですか。
Regexオプションのいずれかに固執する場合は、少なくとも静的変数で RegexOptions.Compiled
を使用します。
public static string ToDigitsOnly(this string input)
{
return new String(input.Where(char.IsDigit).ToArray());
}
これは、メソッドグループに変換されたUsman Zafarの回答に基づいています。
最高のパフォーマンスと低メモリ消費のために、これを試してください:
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, "");
}
}
私のコンピューターでの結果:
初期化...
時間:307
時間: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();
}
所属していません StackOverflow