I've been investigating ways to implement a code highlighting text editor and came across this example: https://archive.codeplex.com/?p=syntaxhighlightbox
However I cannot figure out how to implement multi-line block of comments or strings:
They use this to comment complete lines:
//
// LINES RULES
//
foreach (HighlightLineRule rule in lineRules) {
Regex lineRgx = new Regex(Regex.Escape(rule.LineStart) ".*");
foreach (Match m in lineRgx.Matches(text.Text)) {
text.SetForegroundBrush(rule.Options.Foreground, m.Index, m.Length);
text.SetFontWeight(rule.Options.FontWeight, m.Index, m.Length);
text.SetFontStyle(rule.Options.FontStyle, m.Index, m.Length);
}
}
I tried changing it to:
Regex lineRgx = new Regex(Regex.Escape(rule.LineStart) ".*" Regex.Escape(rule.LineStart));
And although it works using the comment sign on both ends, it doesn't work for multi-line block
Could anyone suggest a solution or point me out for a beginner explanation of this regex as my knowledge of C# is limited and I didn't know about regex before seeing this project.
CodePudding user response:
".*"
is a) greedy, b) stumbles on line endings.
Use
Regex lineRgx = new Regex(Regex.Escape(rule.LineStart) "(?s).*?(?-s)" Regex.Escape(rule.LineStart));
No need adding extra options.
EXPLANATION
----------------------------------------------------------------------------------------------
(?s) enable . to match line ending characters
----------------------------------------------------------------------------------------------
.*? any character (0 or more times
(matching the least amount possible))
----------------------------------------------------------------------------------------------
(?-s) disable . to match line ending characters