wpf richtextbox选择与正则表达式
wpf richtextbox selection with regex
我想为文件的匹配文本着色。
首先,我将文件文本加载到 FileItem.Content 中,然后使用正则表达式获取匹配项,然后将 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);
我想为文件的匹配文本着色。 首先,我将文件文本加载到 FileItem.Content 中,然后使用正则表达式获取匹配项,然后将 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);