regex - 带有正则表达式的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 有什么问题?
解决方案
您正在计算文档开头不可见的“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);
推荐阅读
- python - 在 setup.py 中使用 CUDA 安装 PyTorch
- php - 在每个 Rest API 调用后从股票符号名称列表中更改变量,直到列表在 Wordpress 中完成?
- node.js - '授权:承载未定义'
- javascript - 如何为 div 中的所有输入赋予 value 属性并将其当前值用作值内容?
- sql - old sequelize migration 没有运行,如何重新运行
- react-native - React Native - MaterialCommunityIcons 图标名称的打字稿定义
- ffmpeg - 列出 FFmpeg 中给定复用器支持的编解码器
- python - 创建相似度矩阵的有效方法(熊猫)
- vue.js - 使用 VueJS 将数据从子级发送到父级
- sql - 如何将字符串列分配给变量并在 Bash 脚本的输出中引用它