使用C#在String中查找4个序列号

时间:2015-09-15 14:52:26

标签: c# string

我有一个大字符串,我想在字符串中找到4个序列号。我怎么得到它?

例如:

string a=@"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 a=@"2015/10/13 is my birthday.I love this date1234!"

结果预期:'2015'和'1234'

string a=@"xx888xx88x9xx99x9999xx"

预期结果:'9999'

2 个答案:

答案 0 :(得分:2)

您使用regular expressions执行此操作,例如:

var regex = new Regex(@"\d{4}");            
string a=@"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

答案 1 :(得分:1)

void Main()
{
    string a1 =@" 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