2015-09-15 47 views
-2

我有一個大字符串,我想查找4個字符串中的序列號。我如何得到它?查找字符串中的4個序列號使用C#

例如:

string [email protected]"I(1946) am a string and I have some character and number and some sign like 4412 but I must find 4 sequence numbers in this." 

結果預期: '1946' 和 '4412'

string [email protected]"2015/10/13 is my birthday.I love this date1234!" 

結果預期: '2015' 和 '1234'

string [email protected]"xx888xx88x9xx99x9999xx" 

結果預期:'9999'

+0

'12345' - 的輸出是什麼? –

+0

@UlugbekUmirov mm ...我忘了考慮這個條件 – LorenzoC

回答

2

你d O此與regular expressions,例如:

var regex = new Regex(@"\d{4}");    
string [email protected]"I(1946) am a string and I have some character and number and some sign like 4412 but I must find 4 sequence numbers in this."; 
foreach(Match match in regex.Matches(a)) 
    Console.WriteLine(match.Value); 

活生生的例子:http://rextester.com/OXG80935

+0

感謝您的幫助,這段代碼很好用!我想我必須更多地閱讀正則表達式。 :X – LorenzoC

1
void Main() 
{ 
    string a1 [email protected]" I(1946) am a string and I have some character and number and some sign like 4412 but I must find 4 sequence numbers in this."; 
    string a2 = @" 2015/10/13 is my birthday.I love this date1234!";  
    var reg = @"\d{4}"; 

    Print(Regex.Matches(a1, reg)); 
    Print(Regex.Matches(a2, reg)); 

} 

private void Print(MatchCollection matches) 
{ 
    foreach (Match element in matches) 
    { 
     Console.WriteLine(element.Value); 
    } 
} 

輸出:

1946 
4412 
2015 
1234