首页 > 解决方案 > 带有正则表达式的wpf Richtextbox选择

问题描述

我想为文件的匹配文本着色。首先,我将文件文本加载到FileItem.Content中,然后使用正则表达式获取匹配项,然后将内容放入 Richtextbox 并使用匹配项设置插入符号位置并为文本着色。以及填充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 有什么问题?

在此处输入图像描述

标签: regexwpfselectionrichtextbox

解决方案


您正在计算文档开头不可见的“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);

推荐阅读