match regex

MyWord
       private void btnSearch_Click(object sender, EventArgs e)
        {
            // 清楚文档中的高亮显示
            ClearMark();

            lvSearchResult.Items.Clear();
            if (string.IsNullOrWhiteSpace(tbSearchText.Text))
            {
                return;
            }

            // 按段落检索
            Word.Document currentDocument = Globals.ThisAddIn.Application.ActiveDocument;
            if (currentDocument.Paragraphs != null &&
                currentDocument.Paragraphs.Count != 0)
            {
                foreach (Word.Paragraph paragraph in currentDocument.Paragraphs)
                {
                    MatchCollection mc = Regex.Matches(paragraph.Range.Text, tbSearchText.Text.Trim(), RegexOptions.IgnoreCase);
                    if (mc.Count > 0)
                    {
                        foreach (Match m in mc)
                        {
                            try
                            {
                                int startIndex = paragraph.Range.Start + m.Index;
                                int endIndex = paragraph.Range.Start + m.Index + m.Length;

                                Word.Range keywordRange = currentDocument.Range(startIndex, endIndex);
                                
                                // 获取上下文信息
                                // 获取前两个单词的位置(如果有)
                                startIndex = GetStartPositionForView(paragraph, m, startIndex);

                                // 获取后两个单词的位置(如果有)
                                endIndex = GetEndPositionForView(paragraph, m, endIndex);

                                // 在ListView中展示检索的关键字以及其上下文
                                Word.Range range = currentDocument.Range(startIndex, endIndex);
                                ListViewItem item = new ListViewItem(range.Text);
                                item.Tag = keywordRange;
                                lvSearchResult.Items.Add(item);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                    }
                }
            }
        }

你可能感兴趣的:(regex)