c#找出regex匹配的位置并加粗
c# Find out the position of regex match and bold it
我使用 C# 制作了一个 Win 10 通用应用程序
我想将这两个匹配项的整行加粗。
Run Run = new Run();
Paragraph Paragraph = new Paragraph();
//RichTextBlock = RTB
Run.Text = "D1 abc \n E1 \n F1 \n D1 def";
Paragraph.Inlines.Add(Run);
RTB.Blocks.Add(Paragraph);
string Patter = "D1";
Regex Regex = new Regex(Patter);
MatchCollection Mc = Regex.Matches(Run.Text);
foreach (Match Match in Mc)
{
//bold the D1's lines in the RTB
}
输出:
**D1 abc**
E1
F1
**D1 def**
感谢您的帮助和时间
假设您的文本位于名为 text
:
的变量中
string text = "D1 abc \n E1 \n F1 \n D1 def";
string Patter = "^.*D1.*$";
MatchCollection Mc = Regex.Matches(text, Patter, RegexOptions.Multiline);
int index = 0;
Paragraph.Inlines.Clear();
foreach (Match Match in Mc)
{
//bold the D1's lines in the RTB
Paragraph.Inlines.Add(new Run { Text = text.Substring(index, Match.Index - index) });
var bold = new Bold();
bold.Inlines.Add(new Run { Text = text.Substring(Match.Index, Match.Length) });
Paragraph.Inlines.Add(bold);
index = Match.Index + Match.Length;
}
if (index < text.Length)
{
Paragraph.Inlines.Add(new Run { Text = text.Substring(index) });
}
基本上,我更改了正则表达式以匹配整行而不是仅匹配 "D1"。然后清空段落内容,根据匹配追加正文和粗体。
我使用 C# 制作了一个 Win 10 通用应用程序
我想将这两个匹配项的整行加粗。
Run Run = new Run();
Paragraph Paragraph = new Paragraph();
//RichTextBlock = RTB
Run.Text = "D1 abc \n E1 \n F1 \n D1 def";
Paragraph.Inlines.Add(Run);
RTB.Blocks.Add(Paragraph);
string Patter = "D1";
Regex Regex = new Regex(Patter);
MatchCollection Mc = Regex.Matches(Run.Text);
foreach (Match Match in Mc)
{
//bold the D1's lines in the RTB
}
输出:
**D1 abc**
E1
F1
**D1 def**
感谢您的帮助和时间
假设您的文本位于名为 text
:
string text = "D1 abc \n E1 \n F1 \n D1 def";
string Patter = "^.*D1.*$";
MatchCollection Mc = Regex.Matches(text, Patter, RegexOptions.Multiline);
int index = 0;
Paragraph.Inlines.Clear();
foreach (Match Match in Mc)
{
//bold the D1's lines in the RTB
Paragraph.Inlines.Add(new Run { Text = text.Substring(index, Match.Index - index) });
var bold = new Bold();
bold.Inlines.Add(new Run { Text = text.Substring(Match.Index, Match.Length) });
Paragraph.Inlines.Add(bold);
index = Match.Index + Match.Length;
}
if (index < text.Length)
{
Paragraph.Inlines.Add(new Run { Text = text.Substring(index) });
}
基本上,我更改了正则表达式以匹配整行而不是仅匹配 "D1"。然后清空段落内容,根据匹配追加正文和粗体。