Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

regex

Suppose I have the following string:

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

I have a regex pattern (as specified by the user of the tool I'm writing) of "foobar".

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.

If the pattern were "foo", I'd want to return:

Hello foobar world
Hello foo word

Is this possible?

The code I have is

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

Running this will output:

foobar

Rather than:

Hello foobar world

If string pattern = "foo"; then the output is:

foo
foo

Rather than:

Hello foobar world
Hello foo world

I've also tried:

// ...
Console.WriteLine(m.Result("$_")); // $_ is replacement string for whole input
// ...

But this results in the whole of input for each match in the string (when the pattern is foo):

Hello world
Hello foobar world
Hello foo world
Hello world
Hello foobar world
Hello foo world

like image 308
dx_over_dt Avatar asked Oct 20 '25 13:10

dx_over_dt


2 Answers

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);
}
like image 80
John Prideaux Avatar answered Oct 23 '25 04:10

John Prideaux


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.

like image 36
mrbraitwistle Avatar answered Oct 23 '25 03:10

mrbraitwistle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!