在 C# 中使用正则表达式返回包含匹配项的整行 [英] Return the whole line that contains a match using regular expressions in c#
问题描述
假设我有以下字符串:
string input = "Hello world\n" +
"Hello foobar world\n" +
"Hello foo world\n";
我有一个 "foobar"
的正则表达式模式(由我正在编写的工具的用户指定).
I have a regex pattern (as specified by the user of the tool I'm writing) of "foobar"
.
我想返回与表达式 foobar
匹配的 input
中每一行的整行.所以在这个例子中,输出应该是Hello foobar world
.
I want to return the entire line of each line in input
that match the expression foobar
. So in this example, the output should be Hello foobar world
.
如果模式是 "foo"
,我想返回:
If the pattern were "foo"
, I'd want to return:
你好 foobar 世界
你好 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
而不是:
你好 foobar 世界
Hello foobar world
如果 string pattern = "foo";
那么输出是:
foo
福
而不是:
你好 foobar 世界
世界你好
Hello foobar world
Hello foo world
我也试过:
// ...
Console.WriteLine(m.Result("$_")); // $_ is replacement string for whole input
// ...
但这会导致字符串中每个匹配项的整个 input
(当模式为 foo
时):
But this results in the whole of input
for each match in the string (when the pattern is foo
):
你好世界
你好 foobar 世界
你好 foo 世界
世界你好
你好 foobar 世界
世界你好
Hello world
Hello foobar world
Hello foo world
Hello world
Hello foobar world
Hello foo world
推荐答案
用 .* 和 .* 包围你的正则表达式短语,以便它选择整行.
Surround your regex phrase with .* and .* so that it pick up the entire line.
string pattern = ".*foobar.*";
Regex r = new Regex(pattern)
foreach (Match m in r.Matches(input))
{
Console.WriteLine(m.Value);
}
这篇关于在 C# 中使用正则表达式返回包含匹配项的整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!