使用c#

时间:2015-09-17 18:50:06

标签: c# regex

假设我有以下字符串:

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世界

2 个答案:

答案 0 :(得分:3)

用。*和。*围绕你的正则表达式短语,以便它拿起整行。

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

答案 1 :(得分:1)

是的,这是可能的。您可以使用以下内容:

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

这是因为。字符匹配任何换行符(\ n)字符。

相关问题