【问题标题】:How to implement multi line comment block如何实现多行注释块
【发布时间】:2021-11-16 06:37:17
【问题描述】:

我一直在研究实现代码高亮文本编辑器的方法,并遇到了以下示例: https://archive.codeplex.com/?p=syntaxhighlightbox

但是我不知道如何实现 cmets 或字符串的多行块:

他们用它来评论完整的行:

//
                // 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);
                    }
                }

我尝试将其更改为:

Regex lineRgx = new Regex(Regex.Escape(rule.LineStart) + ".*" + Regex.Escape(rule.LineStart));

虽然它使用两端的注释符号可以工作,但它不适用于多行块

由于我对 C# 的了解有限,并且在看到这个项目之前我不了解正则表达式,因此任何人都可以提出解决方案或指出我对这个正则表达式的初学者解释。

【问题讨论】:

  • 类似new Regex(Regex.Escape(rule.LineStart) + ".*?" + Regex.Escape(rule.LineStart), RegexOptions.Singleline)?
  • 谢谢@WiktorStribiżew,这行得通,请您在答案中详细说明。正如我所说,我是这个正则表达式的新手。

标签: c# regex


【解决方案1】:

".*" 是 a) 贪婪,b) 在行尾绊倒。

使用

Regex lineRgx = new Regex(Regex.Escape(rule.LineStart) + "(?s).*?(?-s)" + Regex.Escape(rule.LineStart));

无需添加额外的选项。

解释

----------------------------------------------------------------------------------------------
(?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

【讨论】:

    猜你喜欢
    • 2014-01-15
    • 1970-01-01
    • 2012-07-19
    • 2010-10-10
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2012-09-06
    相关资源
    最近更新 更多