c# - 在字符串中找到特定的单词并打印剩余的行

标签 c# string

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

字符串示例:

    NumberofCars: 12
    NumberofBikes: 3
    NumberofShoes: 6

假设我想知道字符串中 NumberofBikes 之后的内容,而不是其他任何内容(即 NumberofShoes)。控制台应该只打印“3”。

我想要的代码示例:

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

最佳答案

您可以为此使用 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

关于c# - 在字符串中找到特定的单词并打印剩余的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38126677/

相关文章:

c# - 有什么方法可以在 L2S 身份映射中查找项目?

c# - 列表框内的复选框

Java字符串修剪没有效果

regex - 正则表达式 : replace match with its index

php - 字符串中的无效 JSON 转义序列

javascript - 在 JavaScript 字符串数组中查找子字符串

c# - 返回具有空值的类

c# - TextBox OnClick 事件 - 单击了什么?

c# - BulkCopy WriteToServer() 插入错误列

Python-删除字符串中最后一个字母之前的所有字符