【问题标题】:wpf richtextbox selection with regex带有正则表达式的wpf Richtextbox选择
【发布时间】:2018-11-30 05:32:51
【问题描述】:

我想为文件的匹配文本着色。 首先,我将文件文本加载到 FileItem.Content 中,然后使用正则表达式获取匹配项,然后将 Content 放入富文本框并使用匹配项设置插入符号定位和着色文本。 以及填充richtextbox的代码

    RtbCodes.Document.Blocks.Clear();

    RtbCodes.Document.Blocks.Add(new Paragraph(new Run(item.Content)));
    foreach (Match m in item.Matches)
    {
        TextPointer start1 = RtbCodes.Document.ContentStart.GetPositionAtOffset(m.Index, LogicalDirection.Forward);
        TextPointer end = RtbCodes.Document.ContentStart.GetPositionAtOffset(m.Index + m.Length, LogicalDirection.Backward);
        if (start1 != null && end != null)
        {
            RtbCodes.Selection.Select(start1, end);
            RtbCodes.Selection.ApplyPropertyValue(Run.BackgroundProperty, "red");
        }

    }

我的问题是插入符号选择根本不正确。见下图。 我的正则表达式是 [\$#]{[.a-zA-Z\d]+} ,所以它会得到 #{blacklist.model1} ,但它不是。

那么,richtextbox 有什么问题?

【问题讨论】:

  • 重现问题实际上不需要 html、正则表达式和 FileItem 类。但是他们可以把人们吓跑,因为他们觉得重现你所面临的问题是非常具有挑战性的。如果你提供一个简单的例子——RichTextBox、Paragraph、Run,这些都是演示问题所需要的——你可以很快得到答案——通常在几分钟内。
  • 感谢您的建议。

标签: regex wpf selection richtextbox


【解决方案1】:

您正在计算文档开头不可见的“ElementStart”符号,这就是选择的偏移量不正确的原因。

要获得正确的位置,可以从Run元素的开头开始计数。

var newRun = new Run(item.Content);
RtbCodes.Document.Blocks.Add(new Paragraph(newRun));

TextPointer start1 = newRun.ContentStart.GetPositionAtOffset(m.Index, LogicalDirection.Forward);
TextPointer end = newRun.ContentStart.GetPositionAtOffset(m.Index + m.Length, LogicalDirection.Backward);

【讨论】:

  • 感谢您的回答。但第二场比赛仍然不正确。看第二张图。link
  • 基于您的代码 newRun ,我进行了更改。 ' 变量 i = 0; foreach (在 item.Matches 中匹配 m) { var x = 4 * i; TextPointer start1 = newRun.ContentStart.GetPositionAtOffset(m.Index + x, LogicalDirection.Forward); TextPointer end = newRun.ContentStart.GetPositionAtOffset(m.Index + m.Length + x, LogicalDirection.Backward); ....我++; }' 然后它工作。但是为什么需要 4* 呢?
  • foreach循环中,每次突出显示一个选择时,您都在插入更多“不可见”符号......所以偏移量不断漂移,您可以找出解决方案:首先找出foreach 循环中的所有选择,将它们保存到一个集合中,然后逐个突出显示它们(在另一个 foreach 循环中)。
  • 是的,你是对的。它可以找到。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2010-09-08
  • 2013-11-26
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 2015-01-11
  • 2016-01-11
  • 1970-01-01
相关资源
最近更新 更多