【发布时间】:2022-01-25 13:48:17
【问题描述】:
信息:
我做了一个函数来为richtextbox文本着色,我在richtextbox中打开php配置文件。
错误:
一切正常,当我打开文件时,文本的颜色就像我想要的那样。 但是在我将 RichTextBox 文本保存回文件后,文件类型从“Unix LF”变为“Win CRLF”,并且我设置的颜色出错了。 即使在重新启动应用程序后颜色也是错误的。 如果我手动将 config.php 更改回“Unix LF”,颜色就可以了。 在记事本++中创建任何文本文件为“Unix LF”并手动将其更改为“Win CRLF”,然后在我的应用程序中打开该文件会导致相同的错误。
所以看起来“regExp.Matches”或“richTextBox.Select(match.Index, match.Length)”由于某种原因无法正确匹配文件?
有什么想法吗? 或不同的方法来着色块 cmets? (其他注释类型在我的代码上工作正常,只有块 cmets 有这个错误)
我还尝试在使用正则表达式处理之前将行尾转换为 CRLF,但这并没有影响该错误。
[错误][1] [1]:https://i.stack.imgur.com/92SNu.png
代码:
// READ FILE
public Form_Config()
{
// read config.php
ConfigTextBox.Text = File.ReadAllText("config.php", Encoding.UTF8); // uses RichTextBox
// tested this also to fix the line endings, but no effects on the bug
//ConfigTextBox.Text.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n"); // convert to CRLF
// colorize text box
RichTextBox_Colorize(ConfigTextBox);
}
// SAVE FILE
private void Button_Config_Save_Click(object sender, EventArgs e)
{
ConfigTextBox.SaveFile("config.php", RichTextBoxStreamType.PlainText);
}
// RichTextBox_Colorize
private void RichTextBox_Colorize(RichTextBox richTextBox)
{
// background color
richTextBox.BackColor = Color.Black;
// text color
richTextBox.ForeColor = Color.Yellow;
// comment color
var CommentColor = Color.Lime;
// BUG start
// colorize "/*...*/" block comments (bugs with unix->win files, line endings causing it?)
Regex regExp = new Regex(@"/\*.*?\*/", RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match match in regExp.Matches(richTextBox.Text))
{
richTextBox.Select(match.Index, match.Length);
richTextBox.SelectionColor = CommentColor;
}
// BUG end
// colorize "#" comments (works fine, no bugs)
Regex regExp2 = new Regex(@"#(.*)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
foreach (Match match in regExp2.Matches(richTextBox.Text))
{
richTextBox.Select(match.Index, match.Length);
richTextBox.SelectionColor = CommentColor;
}
// colorize "//" comments (works fine, no bugs)
Regex regExp3 = new Regex(@"//(.*)", RegexOptions.IgnoreCase | RegexOptions.Multiline);
foreach (Match match in regExp3.Matches(richTextBox.Text))
{
richTextBox.Select(match.Index, match.Length);
richTextBox.SelectionColor = CommentColor;
}
// scroll caret back to start
richTextBox.Select(0,0);
richTextBox.ScrollToCaret();
}
【问题讨论】:
标签: regex richtextbox