2015-07-28 3 views
0

Вот код, который у меня есть, он отлично работает, но мне нужно его искать, чтобы найти более одного слова и выделить все слова из списка, который я ему даю.Поиск и выделение нескольких текстов

Итак, скажем, у меня есть поиск «Закрыть», и он выделяет все слова, содержащие этот Красный. Ну, как я могу это сделать, чтобы выделить больше слов, чем просто «Закрыть». Так что он одновременно искать несколько текста, например, "Закрыть" & & "Enter" & & "Оставить"


private void btn_Search_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     if (richTextBox1.Text != string.Empty) 
     { 
      // if the ritchtextbox is not empty; highlight the search criteria 
      int index = 0; 
      String temp = richTextBox1.Text; 
      richTextBox1.Text = ""; 
      richTextBox1.Text = temp; 
      while (index < richTextBox1.Text.LastIndexOf("Close")) 
      { 
       richTextBox1.Find("Close", index, richTextBox1.TextLength, RichTextBoxFinds.None); 
       richTextBox1.SelectionColor = Color.Cyan; 
       index = richTextBox1.Text.IndexOf("Close", index) + 1; 
       richTextBox1.Select(); 
      } 
     } 
    } 
} 

ответ

0

Это работает для меня:

// using System.Text.RegularExpressions; 

string[] searchTerms = new[] { "Close", "Enter", "Leave" }; 

// if the richtextbox is not empty; highlight the search criteria 
if (richTextBox1.Text != string.Empty) 
{ 
    // reset the selection 
    string text = richTextBox1.Text; 
    richTextBox1.Text = ""; 
    richTextBox1.Text = text; 
    // find all matches 
    foreach (Match m in new Regex(string.Join("|", searchTerms.Select(t => t.Replace("|", "\\|")))).Matches(richTextBox1.Text)) 
    { 
     // for each match, select and then set the color 
     richTextBox1.Select(m.Index, m.Length); 
     richTextBox1.SelectionColor = Color.Cyan; 
    } 
} 
0

Вы можете попробовать это:

private void btn_Search_Click(object sender, EventArgs e) 
{ 
    var wordsToHighlight = new List<string>() 
    { 
     "Exit", "Close", "Leave" 
    }; 

    if (!string.IsNullOrWhiteSpace(richTextBox1.Text)) 
    { 
     foreach (var word in wordsToHighlight) 
     { 
      int index = 0; 
      while (index != -1) 
      { 
       richTextBox1.SelectionColor = Color.Cyan; 
       index = richTextBox1.Find(word, index + word.Length - 1, richTextBox1.TextLength, RichTextBoxFinds.None); 
      } 
     } 
    } 
} 

Пример (я изменил SelectionColor на красный, потому что это легче заметить):

Example of highlighting

Смежные вопросы