簡體   English   中英

為什么此Regex.Match失敗?

[英]Why is this Regex.Match failing?

我有這個小方法來查找字符串中的3位數字並將其遞增1。 我傳遞的字符串類型類似於CP1-P-CP2-004-DMOT03-C-FP04-003

char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();

foreach (char c in alphabet)
{
    m = Regex.Match(s, @"\d{3}(?=[" + c + "-]|$)");
}

if (m.Success)
{
    int i = Convert.ToInt32(m.Value); i += 1;
    Console.WriteLine(s + " - " + i.ToString("D3"));
}
else { Console.WriteLine(s + " - No success"); }

編輯:最初我只是這個; 測試我的Regex.Match案例:

Match m = Regex.Match(s, @"\d{3}(?=[A-]|$)");

它可以與CP1PCP2001A一起使用,不用擔心,但是當我對其進行更新並嘗試使用CP1PCP2001C它返回了“ No Success”,而CP1PCP2001沒有問題。 誰能告訴我為什么呢?

你有沒有嘗試過

m = Regex.Match(s, @"\d{3}(?=[A-Z\-]|$)");

[AZ]表示它可以是A到Z之間的任何一個大寫字母,從而消除了對char[] alphabet的需要,並且\\-允許您添加'-'作為參數,而不會引起與第一個參數的沖突。

從注釋中,我們正在尋找“前3位數字(從右側開始)”。 這是一個文字實現:

m = Regex.Match(s, @"\d{3}", RegexOptions.RightToLeft);

比起其他答案,這更適合於意外字符。 您可以決定這對您的應用程序是好是壞。

用這種方式重寫代碼

bool matched = false;
foreach (char c in alphabet)
{
    m = Regex.Match(s, @"\d{3}(?=[" + c + "-]|$)");

    if (m.Success)
    {
        int i = Convert.ToInt32(m.Value); i += 1;
        Console.WriteLine(s + " - " + i.ToString("D3"));
        matched=true;
        break;
    }
}
if(!matched)
    Console.WriteLine(s + " - No success");

更好的方法是不循環並在正則表達式本身中指定要匹配的char范圍

    m = Regex.Match(s, @"\d{3}(?=[A-Z\-]|$)");

    if (m.Success)
    {
        int i = Convert.ToInt32(m.Value); i += 1;
        Console.WriteLine(s + " - " + i.ToString("D3"));
    }
    else
       Console.WriteLine(s + " - No success");

regex 演示在這里

暫無
暫無

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

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