我有一个字符串,我想在其中找到一个特定的词,然后打印包含该词的行的其余部分。
字符串示例:
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/