2017-08-07 126 views
-1

我有一個字符串"offerDate(1,30)"。我必須檢查我的字符串是否以"offerDate"開頭,如果這個條件是真的,我必須從字符串中提取1和30。任何人都可以幫助我。提前致謝。正則表達式字符串「offerDate(1,30)」

我的代碼是

System.Text.RegularExpressions.Regex.Matches("StingToBePassed",@"\d+") 
    .Cast<Match>() 
    .Select(x => Convert.ToInt16(x.Value)) 
    .ToList(); 
+0

請說明您當前的代碼有什麼問題 –

+0

我只是想檢查我的字符串是否以「offerDate」開頭。如果它是真的,那麼只有我需要存儲這個數字。當前的代碼提取數字並存儲在列表中,但是它不檢查字符串是否以「OfferDate」開頭 –

+0

要澄清,「StringToBePassed」可以包含'offerDate(1,30)'的_多個實例嗎?我更新的答案假定您使用'Match'的倍數,但如果這個假設是錯誤的,我可以恢復到我的原始版本,它只解析一個實例。 –

回答

0

您可以使用組來提取較大的圖案的特定部分。你的情況:

offerDate\((\d+),(\d+)\) 

然後您可以封裝成函數:

static IEnumerable<Range> ParseOfferDateRanges(string input) 
{ 
    var matches = Regex.Matches(input, @"offerDate\((\d+),(\d+)?\)"); 

    return matches 
     .Cast<Match>() 
     .Select(ParseOfferDateMatch) 
     .ToList(); 
} 

static Range ParseOfferDateMatch(Match match) 
{ 
    var fromValue = match.Groups[1].Value; 
    var toGroup = match.Groups[2]; 

    var to = toGroup.Success 
     ? short.Parse(toGroup.Value) 
     : (short?)null; 

    return new Range() 
    { 
     From = short.Parse(fromValue), 
     To = short.Parse(toValue) 
    }; 
} 

我假設你有一個Range結構,看起來像以下,但在C#7,你還可以返回一個元組:

public struct Range 
{ 
    public short From; 
    public short? To; 
} 
+0

非常感謝。這是我想要的同樣的事情。 –

+0

沒問題。如果它回答了你的問題,你可以點擊我的答案上的「打勾」,它會將你的問題標記爲「已回答」。 –

+0

感謝您的幫助。但是,是否有可能將第二個參數設置爲可選。我的意思是如果提供字符串「OfferDate(1,)」,那麼它也與條件匹配。我們絕對可以使用兩個正則表達式,但我希望它使用單個表達式 –

0

你可以嘗試用積極的回顧後功能模式:

(?<=offerDate\((\d+,)?)\d+

注意:您必須使用regex.Matches(而不僅僅是Match)才能工作。