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

4

假设我有以下字符串:

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

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

我希望返回与表达式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

2个回答

10

用 .* 和 .* 包围您的正则表达式,以便它可以捕获整行。

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

1
好的。现在我感觉自己像个白痴。在某种情况下(就是我提出问题的那个),我准备对input.Split('\n')中的每一行运行正则表达式,而如果用户指定了输出模式,则只对input运行。你的解决方案更简单。 - dx_over_dt

1
是的,这是可能的。您可以使用以下内容:
Regex.Matches(input, @".*(YourSuppliedRegexHere).*");

这能够工作是因为 . 字符匹配除了换行符(\n)之外的任何字符。

是的,那就是我最终所做的。起初我不想改变模式,因为用户指定了它,而不是我的代码,但这很简单。 - dx_over_dt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接