簡體   English   中英

如何在C#中使用正則表達式匹配規則

[英]how to match rules using regex in C#

我是C#中的正則表達式新手。 我不確定如何使用正則表達式來驗證客戶端參考號。 該客戶參考號具有3種不同的類型:id,手機號和序列號。

C#:

string client = "ABC 1234567891233";

//do code stuff here:
if Regex matches 3-4 digits to client, return value = client id
else if Regex matches 8 digts to client, return value = ref no
else if Regex matches 13 digits to client, return value = phone no

我不知道如何使用正則表達式對不同類型的數字進行計數。 就像Regex(“ {![\\ d .....}”))。

我不明白為什么您會在這里使用正則表達式。 一個簡單的單線便可以做到,例如。 甚至是這樣的擴展方法:

static int NumbersCount(this string str)
{
    return str.ToCharArray().Where(c => Char.IsNumber(c)).Count();
}

我認為它更清晰,更可維護。

您可能可以通過組匹配以及類似的方式進行嘗試

"(?<client>[0-9]{5,9}?)|(?<serial>[0-9]{10}?)|(?<mobile>[0-9]{13,}?)"

然后,您將檢查“ client”,“ serial”,“ mobile”是否匹配,並在此基礎上解釋輸入的字符串。 但是更容易理解嗎?

對於以后閱讀代碼的人,它是否更清楚地表達了您的意圖?

如果要求是這些數字必須是連續的(如@Corak指出的那樣)...我仍然會迭代地編寫它,如下所示:

/// <summary>
/// returns lengths of all the numeric sequences encountered in the string
/// </summary>        
static IEnumerable<int> Lengths(string str)
{
    var count = 0;
    for (var i = 0; i < str.Length; i++)
    {
        if (Char.IsNumber(str[i]))
        {
            count++;
        }
        if ((!Char.IsNumber(str[i]) || i == str.Length - 1) && count > 0)
        {
            yield return count;                
            count = 0;                    
        }
    }
}

然后您可以簡單地:

bool IsClientID(string str)
{
    var lenghts = Lengths(str);
    return lenghts.Count() == 1 && lenghts.Single() == 5;            
}

更詳細嗎? 是的,但是人們可能仍然會喜歡您,而不是每次驗證規則發生變化或需要進行一些調試時都讓他們對正則表達式擺弄:)這包括您的未來自我。

我不確定是否理解您的問題。 但是,如果要從字符串中獲取數字字符的數量,可以使用以下代碼:

Regex regex = new Regex(@"^[0-9]+$");
string ValidateString = regex.Replace(ValidateString, "");
if(ValidateString.Length > 4 && ValidateString.Length < 10)
    //this is a customer id
....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM