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
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With