C# Regex - Find Comments Example

CSharp · Console

/Program.cs

using System;
using System.Text.RegularExpressions;

string multiLineText = 
    """
    This is some sample text.
    # This is a comment.
    And here's another line.
    # Another comment.
    """;

foreach (var comment in FindComments(multiLineText))
{
    Console.WriteLine(comment);
}

static string[] FindComments(string input)
{
	// Use RegexOptions.Multiline to treat ^ as the start of each line.
	Regex commentRegex = new Regex("^#.*$", RegexOptions.Multiline);

	var matches = commentRegex.Matches(input);
	string[] comments = new string[matches.Count];
	for (int i = 0; i < matches.Count; i++)
	{
		comments[i] = matches[i].Value;
	}

	return comments;
}
;