使用c#中的正则表达式返回包含匹配项的整行

本文关键字:包含匹 返回 正则表达式 使用 | 更新日期: 2023-09-27 18:13:08

假设我有以下字符串:

string input = "Hello world'n" + 
               "Hello foobar world'n" +
               "Hello foo world'n";

我有一个"foobar"的正则表达式模式(由我正在编写的工具的用户指定)。

我想返回input中匹配表达式foobar的每行的整行。因此,在本例中,输出应该是Hello foobar world

如果模式是"foo",我想返回:

Hello foobar world
Hello foo word

这可能吗?

代码是

string pattern = "foobar";
Regex r = new Regex(pattern)
foreach (Match m in r.Matches(input))
{
    Console.WriteLine(m.Value);
}

运行此命令将输出:

foobar

而不是:

Hello foobar world

如果string pattern = "foo";,则输出为:

foo
foo

而不是:

Hello foobar world
Hello foo world

我也试过了:

// ...
Console.WriteLine(m.Result("$_")); // $_ is replacement string for whole input
// ...

但是这会导致对于字符串中的每个匹配(当模式为foo时)的整个input:

Hello world
Hello foobar world
Hello foo world
Hello world
Hello foobar world
Hello foo world

使用c#中的正则表达式返回包含匹配项的整行

用。*和。*包围你的regex短语,以便它拾取整行。

string pattern = ".*foobar.*";
Regex r = new Regex(pattern)
foreach (Match m in r.Matches(input))
{
     Console.WriteLine(m.Value);
}

是的,这是可能的。您可以使用以下命令:

Regex.Matches(input, @".*(YourSuppliedRegexHere).*");

之所以有效是因为。字符匹配除换行符('n)字符以外的任何