dx_over_dt
dx_over_dt

Reputation: 14328

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

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

Upvotes: 4

Views: 13945

Answers (2)

mrbraitwistle
mrbraitwistle

Reputation: 414

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.

Upvotes: 1

John Prideaux
John Prideaux

Reputation: 358

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);
}

Upvotes: 10

Related Questions