供参考,此代码来自以下问题的答案:
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
private class TextSearcher
{
private BindingSource m_bsMatches = null;
private RichTextBox m_Rtb = null;
public TextSearcher(RichTextBox rtb) : this(rtb, Color.Yellow, Color.Red) { }
public TextSearcher(RichTextBox rtb, Color selectionColor, Color currentColor)
{
this.m_Rtb = rtb;
SelectionColor = selectionColor;
CurrentColor = currentColor;
}
public string CurrentKeywords { get; private set; } = string.Empty;
public bool CaseSensitive { get; set; } = true;
public int CurrentIndex => m_bsMatches.Position;
public Match CurrentMatch => (Match)m_bsMatches.Current;
public MatchCollection Matches { get; private set; }
public Color SelectionColor { get; set; }
public Color CurrentColor { get; set; }
public void GotoMatch(int position)
{
SelectText(false);
this.m_bsMatches.Position = Math.Max(Math.Min(this.m_bsMatches.Count, position), 0);
SelectText(true);
}
public void NextMatch()
{
SelectText(false);
if (this.m_bsMatches != null && m_bsMatches.Position == this.m_bsMatches.Count - 1)
{
this.m_bsMatches.MoveFirst();
}
else
{
this.m_bsMatches.MoveNext();
}
SelectText(true);
}
public void PreviousMatch()
{
SelectText(false);
if (this.m_bsMatches != null && this.m_bsMatches.Position > 0)
{
this.m_bsMatches.MovePrevious();
}
else
{
this.m_bsMatches.MoveLast();
}
SelectText(true);
}
public int Search(string keywords)
{
if (CurrentKeywords.Equals(keywords)) return Matches.Count;
this.m_bsMatches?.Dispose();
CurrentKeywords = keywords;
var options = RegexOptions.Multiline |
(CaseSensitive ? RegexOptions.IgnoreCase : RegexOptions.None);
Matches = Regex.Matches(this.m_Rtb.Text, keywords, options);
if (Matches != null)
{
this.m_Rtb.SelectAll();
this.m_Rtb.SelectionColor = this.m_Rtb.ForeColor;
this.m_Rtb.SelectionStart = 0;
this.m_bsMatches = new BindingSource(Matches, null);
SelectKeywords();
return Matches.Count;
}
return 0;
}
private void SelectKeywords()
{
foreach (Match m in Matches)
{
SelectText(false);
NextMatch();
}
this.m_bsMatches.MoveFirst();
}
private void SelectText(bool current)
{
this.m_Rtb.Select(CurrentMatch.Index, CurrentMatch.Length);
this.m_Rtb.SelectionColor = current ? CurrentColor : SelectionColor;
}
}
使用中:
numericUpDown1.Maximum = rbsearcherhl.Search(textBox1.Text);
例如,textBox1中的文本为"System"
,但是在我要搜索多个单词的搜索中,您添加了,,
,例如System,,public
或system,,public,,World
但是在TextSearcher调用中的搜索功能中,使用符号|
来搜索多个单词>
如何在搜索器中进行更改,使符号像我的,,
?
在示例中,您键入System|using
来搜索多个单词但我想通过键入System,,using
或System,,using,,public,,World
代替|
如何使用,,
作为参考,此代码来自以下问题的答案:以一个不同于RichTextBox文本中所有其他选择的颜色突出显示一个单词或短语?使用System.Collections ....
将用户在您的文本框1(或您所说的文本框)中键入的System,,public
用作[]并提供给TextSearcher,>
Search(textbox1.Text.Replace("|", "\\|").Replace(",,", "|"))