[英]How to select text between two characters in a RichTextBox
我有一個 RichTextBox,用於記錄有關我的應用程序的信息。 這是它可能記錄的內容的示例:
<22:52:21:179> Starting Argo Studio
<22:52:22:731> Argo Studio has finished starting
<22:52:30:41> Time to load commands: 00:00:00.00
<22:52:30:48> Created 'App 1'
<
和>
之間的文本是時間。
我需要將時間的顏色更改為灰色。
以前,我這樣做:
for (int i = 0; i < RichTextBox.Lines.Length; i++)
{
int indexStart = RichTextBox.GetFirstCharIndexFromLine(i);
int indexEnd = RichTextBox.Lines[i].Split(' ')[0].Length;
RichTextBox.Select(indexStart, indexEnd);
RichTextBox.SelectionColor = Color.Gray;
}
但是,這不再對我有用,因為現在我有多行日志:
<23:0:4:320> Error-h88tzd: The source and destination are the same.
Source: 'C:\Users\user\Dropbox\PC\Desktop\...'.
Destination: 'C:\Users\user\Dropbox\PC\Desktop\....
More information: https://
如果> or <
不存在,您可以跳過該行。 試試這個:
RichTextBox.AppendText("< 22:52:21:179 > Starting Argo Studio" +
"\r\n" + "<22:52:22:731 > Argo Studio has finished starting" +
"\r\n" + "<22:52:30:41 > Time to load commands: 00:00:00.00" +
"\r\n" + "< 22:52:30:48 > Created 'App 1'" +
"\r\n" + "23:0:4:320 Error - h88tzd: The source and destination are the same." +
"\r\n" + @"Source: 'C:\Users\user\Dropbox\PC\Desktop\...'." +
"\r\n" + @"Destination: 'C:\Users\user\Dropbox\PC\Desktop\...." +
"\r\n" + "More information: https:/");
for (int i = 0; i < RichTextBox.Lines.Length; i++)
{
int indexStart = RichTextBox.Lines[i].IndexOf("<");
int indexEnd = RichTextBox.Lines[i].LastIndexOf(">");
if (indexStart < 0 || indexEnd < 0)
continue;
int baseIndex = RichTextBox.Text.IndexOf(RichTextBox.Lines[i]);
RichTextBox.Find(RichTextBox.Lines[i].Substring(indexStart+1, indexEnd-1));
RichTextBox.SelectionColor = Color.Gray;
}
然后結果:
希望這可以幫助!
您可以使用Regex.Matches查找與時間戳匹配的所有文本部分。
每個Match object 返回找到匹配項的字符Index
和匹配字符串的Length
。
此信息可用於執行選擇。
文本是否換行並不重要,因為考慮了整個文本。
例如:
var matches = Regex.Matches(richTextBox.Text, @"<*\d+:\d+:\d+:\d+>*", RegexOptions.Multiline);
foreach (Match m in matches) {
richTextBox.SelectionStart = m.Index;
richTextBox.SelectionLength = m.Length;
richTextBox.SelectionColor = Color.Gray;
}
不太清楚你是否想要 select 時間戳在這里:
Time to load commands: 00:00:00.00
如果你這樣做,需要做一些小改動(例如,將模式設置為<*\d+:\d+:\d+[:.]\d+>*
)
如果您只想要尖括號中的時間戳,則<\d+:\d+:\d+:\d+>
僅當該行包含<
和>
時,才設置顏色格式
for (int i = 0; i < RichTextBox.Lines.Length; i++)
{
if (RichTextBox.Lines[i].Contains("<") &&
RichTextBox.Lines[i].Contains(">"))
{
int indexStart = RichTextBox.GetFirstCharIndexFromLine(i);
int indexEnd = RichTextBox.Lines[i].Split(' ')[0].Length;
RichTextBox.Select(indexStart, indexEnd);
RichTextBox.SelectionColor = Color.Gray;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.