Return the whole line that contains a match using regular expressions in c#

后端 未结 2 1392
清歌不尽
清歌不尽 2021-01-22 22:59

Suppose I have the following string:

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


        
相关标签:
2条回答
  • 2021-01-22 23:11

    Yes, this is possible. You can use the following:

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

    This works because the . character matches anything but the newline (\n) chracter.

    0 讨论(0)
  • 2021-01-22 23:23

    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);
    }
    
    0 讨论(0)
提交回复
热议问题