簡體   English   中英

正則表達式使用字符串C#中的數字匹配多個出現次數

[英]Regex Match multiple occurences with numbers in string C#

我一直在尋找我的問題答案,但找不到,所以我在這里寫。

我想以字符串為例:=“37513220102304920105590”

並找到長度為11且從3或4開始的所有匹配項。

我一直試圖這樣做:

string input = "37513220102304920105590"
var regex = new Regex("^[3-4][0-9]{10}$");
var matches = regex.Matches(trxPurpose);

// I expect it to have 3 occurances "37513220102", "32201023049" and "30492010559"
// But my matches are empty. 
foreach (Match match in matches)
{
    var number = match.Value;

    // do stuff
}

我的問題是:我的正則表達式是壞的還是我做錯了什么?

在正向前瞻中使用捕捉,你也需要移除錨點。 注意-34之間是多余的。

(?=([34][0-9]{10}))

請參閱正則表達式演示

在C#中,由於捕獲了值,您需要收集.Groups[1].Value內容,請參閱C#代碼

var s = "37513220102304920105590";
var result = Regex.Matches(s, @"(?=([34][0-9]{10}))")
        .Cast<Match>()
        .Select(m => m.Groups[1].Value)
        .ToList();

暫無
暫無

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

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