在richtextbox wpf c#中使用正则表达式和更新文本 [英] Using Regex and updating text in richtextbox wpf c#
本文介绍了在richtextbox wpf c#中使用正则表达式和更新文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里有我的一段代码:
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("Hello")))));
string myText = new TextRange(mainWindow.richtextbox2.Document.ContentStart, mainWindow.richtextbox2.Document.ContentEnd).Text;
//replace two or more consecutive spaces with a single space, and
//replace two or more consecutive newlines with a single newline.
var str = Regex.Replace(myText, @"( |\r?\n)\1+", "$1", RegexOptions.Multiline);
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run(str)))));
我知道 Hello 一开始会是多余的.我想同时删除此冗余,我还想删除每个文本行中的间距.这是我在运行 3 次时截取的屏幕截图.
I know that Hello will be redundant at first start. I want to remove this redundancy at the same time, I also want to remove the spacing in every textline. This is the screenshot that I have taken during my 3 runs.
我该如何解决这个问题?请修改代码.
How can I fix this? Please modify the code.
已这是我更改 Richtextbox 的 XAML 后的屏幕截图.我怎样才能让它从第一行开始?
EDITED: Here is now the screenshot after I change the XAML of richtextbox. How can I make it start at the very first line?
推荐答案
在 xaml 中试试这个(我做了演示):
Try this in xaml (i made demo):
<RichTextBox HorizontalAlignment="Left" Height="100" Margin="190,83,0,0" VerticalAlignment="Top" Width="100">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
<FlowDocument>
<Paragraph>
<Run Text="RichTextBox"/>
</Paragraph>
</FlowDocument>
</RichTextBox>
在代码中:
//这可以添加到你的调用方法中
//this can be added in your invoke method
mainWindow.Dispatcher.Invoke(new Action(() => DoSomething));
private void DoSomething(){
string myText = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
var resultString = Regex.Replace(myText, @"( |\r?\n)\1+", "$1");
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(resultString));
richTextBox.SelectAll();
richTextBox.Selection.Load(stream, DataFormats.Text);
}
这篇关于在richtextbox wpf c#中使用正则表达式和更新文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文