在字符串中找到特定单词并打印其余行

时间:2016-06-30 14:52:03

标签: c# string

我有一个字符串,我想在其中找到一个特定的单词,然后打印包含该单词的其余部分。

字符串示例:

    NumberofCars: 12
    NumberofBikes: 3
    NumberofShoes: 6

所以说我想知道字符串中的NumberofBikes之后会发生什么,而不是其他任何东西(即NumberofShoes)。控制台应该只打印“3”。

我想要的代码示例:

    if string.Contains("NumberofBikes")
    {
      Console.Writeline(Rest of that line);
    }

1 个答案:

答案 0 :(得分:1)

您可以使用Regex。搜索您的单词,然后搜索一组数字(假设您将始终拥有要捕获的数字)。捕获组允许您获取值。以下是示例代码:

// The original string to search within.
string s = "NumberofCars: 12\r\nNumberofBikes: 3\r\nNumberofShoes: 6";
// The search value.
string search = "NumberofBikes";
// Define a regular expression for executing the search.
Regex rgx = new Regex(search + @".*?(\d+?)", RegexOptions.IgnoreCase);
// Find matches.
MatchCollection matches = rgx.Matches(s);
if (matches.Count > 0 && matches[0].Groups.Count > 1) //At least one match was found and has a capturing group.
{
    Console.WriteLine(matches[0].Groups[1]); //Return the first capturing group of the first match.
}

您可以看到demo here

相关问题