使用c#中的正则表达式返回包含匹配项的整行
假设我有以下字符串:
string input = "Hello world\n" + "Hello foobar world\n" + "Hello foo world\n";
我有"foobar"
的正则表达式模式(由我正在编写的工具的用户指定)。
我想返回input
中与表达式foobar
匹配的每一行的整行。 所以在这个例子中,输出应该是Hello foobar world
。
如果模式是"foo"
,我想要返回:
你好foobar世界
你好foo字
这可能吗?
我的代码是
string pattern = "foobar"; Regex r = new Regex(pattern) foreach (Match m in r.Matches(input)) { Console.WriteLine(m.Value); }
运行此将输出:
foobar的
而不是:
你好foobar世界
如果string pattern = "foo";
然后输出是:
FOO
FOO
而不是:
你好foobar世界
你好foo世界
我也尝试过:
// ... Console.WriteLine(m.Result("$_")); // $_ is replacement string for whole input // ...
但这会导致字符串中每个匹配的整个input
(当模式为foo
):
你好,世界
你好foobar世界
你好foo世界
你好,世界
你好foobar世界
你好foo世界
用。*和。*包围你的正则表达式短语,以便它拿起整行。
string pattern = ".*foobar.*"; Regex r = new Regex(pattern) foreach (Match m in r.Matches(input)) { Console.WriteLine(m.Value); }
是的,这是可能的。 您可以使用以下内容:
Regex.Matches(input, @".*(YourSuppliedRegexHere).*");
这是因为。 字符匹配除换行符(\ n)之外的任何内容。