문제

프로젝트의 요구 사항을 빠르게 추가합니다. 전화 번호를 보유하는 DB의 필드는 10 자만 허용하도록 설정되어 있습니다. "(913) -444-5555"또는 다른 것들이 지나면 어떤 종류의 특수 교체 함수를 통해 문자열을 실행할 수있는 빠른 방법이 있습니까?

Regex?

도움이 되었습니까?

해결책

확실히 regex :

string CleanPhone(string phone)
{
    Regex digitsOnly = new Regex(@"[^\d]");   
    return digitsOnly.Replace(phone, "");
}

또는 클래스 내에서 Regex를 다시 만들지 않도록 : 항상 다음과 같습니다.

private static Regex digitsOnly = new Regex(@"[^\d]");   

public static string CleanPhone(string phone)
{
    return digitsOnly.Replace(phone, "");
}

실제 입력에 따라 1 인의 선행 (장거리) 또는 X 또는 X (확장)를 추적하는 것과 같은 추가 논리를 원할 수 있습니다.

다른 팁

REGEX로 쉽게 할 수 있습니다.

string subject = "(913)-444-5555";
string result = Regex.Replace(subject, "[^0-9]", ""); // result = "9134445555"

Regex를 사용할 필요가 없습니다.

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, "");
    }
}

내 컴퓨터의 결과는 다음과 같습니다.
init ...
시간 : 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();
        }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top