我写了一个真空管交叉参考程序。 我不知道如何迭代 RichTextBox1 以使请求的管值变为粗体。
搜索 6AU8A 时的现有输出
Tube Cross1 Cross2 Cross3 Qty Location
6AU8 6AU8A 6BH8 6AW8 2 PM BOX 3
6AU8A 6AU8 6BH8 6AW8 6 BOX 9
6BA8A 6AU8 6AU8A 8AU8A 1 BOX 11
6CX8 6AU8A 6EB8 6GN8 2 BOX 16
6EH5 6AU8A 2081 6AW8A# 1 BOX 19
6GH8 6EA8 6GH8A 6AU8A 2 BOX 23
6GH8A 6GH8 6EA8 6AU8A 10 BOX 22
6GH8A 6GH8 6EA8 6AU8A 5 BOX 23
因此,我需要以粗体出现任何搜索词(本例中为 6AU8A)。 使用 VS 2019,针对 .NET 4.8.1 编译的 Windows 应用程序可在 Windows 7 和 10 PC 上运行。
public int FindMyText(string text)
{
length = text.Length;
// Initialize the return value to false by default.
int returnValue = -1;
// Ensure that a search string has been specified and a valid start point.
if (text.Length > 0)
{
// Obtain the location of the first character found in the control
// that matches any of the characters in the char array.
int indexToText = richTextBox1.Find(text);
// Determine whether the text was found in richTextBox1.
if (indexToText >= 0)
{
// Return the location of the character.
returnValue = indexToText;
start = indexToText;
}
}
return returnValue;
}
一旦调用
Find()
,该值将被选择(如果存在)。然后您可以更改字体以包括粗体。 Find()
函数有一个“开始”位置,可让您找到下一个出现的位置。因此,您从 0 开始,然后添加搜索字符串的长度以获得下一个起始位置。如果返回的值为 -1,则不再有匹配项,您可以停止。
看起来像这样:
private void button1_Click(object sender, EventArgs e)
{
BoldText("6AU8A"); // get your input from somewhere...
}
private void BoldText(String value)
{
int startAt = 0;
int indexToText = richTextBox1.Find(value, startAt, RichTextBoxFinds.None);
while (indexToText != -1)
{
richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
startAt = startAt + value.Length;
indexToText = richTextBox1.Find(value, startAt, RichTextBoxFinds.None);
}
}
这是在行动:
如果您确实需要为此使用 RichTextBox,则可以使用简单的正则表达式来匹配一个或多个 terms,然后使用每个匹配的
Index
和 Length
属性来执行选择并更改字体和/或其他样式(在此处的代码中,可选颜色)
将要匹配的术语集合(包含一个或多个术语)传递给方法:
string[] parts = { "6AU8A", "6GH8" };
Highlight(richTextBox1, parts, FontStyle.Bold);
// also specifying a Color
Highlight(richTextBox1, parts, FontStyle.Bold, Color.Red);
// or deselect previous matches
Highlight(richTextBox1, parts, FontStyle.Regular);
正则表达式仅匹配完整序列,例如,传递
6GH8
,它不会部分突出显示 6GH8A
\b
边界
using System.Text.RegularExpressions;
private void Highlight(RichTextBox rtb, IEnumerable<string> terms, FontStyle style, Color color = default)
{
color = color == default ? rtb.ForeColor : color;
string pattern = $@"\b(?:{string.Join("|", terms)})\b";
var matches = Regex.Matches(rtb.Text, pattern, RegexOptions.IgnoreCase);
using (var font = new Font(rtb.Font, style)) {
foreach (Match m in matches) {
rtb.Select(m.Index, m.Length);
rtb.SelectionColor = color;
rtb.SelectionFont = font;
};
}
}