A couple of regex recipes in C#


For my own reference. Hope it’s helpful to you as well.

Given this text pattern:
Keyword blah blah keyword blah
Line I don’t care.
Keyword blah blah keyword blah
I want everything after this line.
Good stuff
Good stuff

Recipe 1: Returning all lines with keyword:
[code language=”c#”]
//string pattern = @”keyword .+ keyword .+”;
public string GetKeywordLines(string pattern, string inputText)
{
StringBuilder sb = new StringBuilder();
foreach (Match m in Regex.Matches(inputText, pattern))
{
sb.AppendLine(m.Value);
}
return sb.ToString();
}
[/code]
Recipe 2: Returning all lines after “I want everything after this line.”
[code language=”c#”]
//string pattern = @”^.+I want everything after this line\.(.+)$”;
public string SplitStatusUpdate(string pattern, string inputText)
{
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = regex.Match(inputText);
return m.Groups[1].Value;
}
[/code]]

,

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.