Is there any way in C# to use a Regex, but only return (with a Regex.Match) a part of the Regex? For example,
string input = "Hello my friend!";
string pattern = "\\w+ my friend.";
Console.WriteLine(Regex.Match(input, pattern)); //Returns "Hello my friend!"
But what if I just wanted the “Hello”, or maybe just the punctuation at the end? I know I could do something like “^\\w+” (or even just .split(' ')[0]), but then that would match the first word of any input, and I’d only like it to match the first word if the rest of it matches with ” my friend.” Is there any way to do this, or would it be simpler just to do
string input = "Hello my friend!";
string pattern = "\\w+ my friend.";
if (Regex.IsMatch(input, pattern))
{
Console.WriteLine(input.Split(' ')[0]);
}
else
{
Console.WriteLine("");
}
(sorry if this is really simple or if I’m missing something, I’ve just started really using Regexs)
Thanks,
Matthew
Apart form the capturing groups suggested in other answers, you can also use a lookahead. So you can use an expression like
"\\w+(?= my friend)"and the entire match will only return the\\w+part.In general, a pattern in the form
a(?=b)whereaandbare regular expressions matchesaonly if it is followed bybbut does not matchb.