如何获取ITextDocument的特定单词范围

时间:2018-11-03 09:43:53

标签: c# uwp

我遇到一个问题,我想在ITextDocument中找到一个单词,然后找到它的范围(使范围字符格式加粗并全部显示)

示例:我想在字符串“嘿,嗨,你好”中将“ hello”一词变为粗体

1 个答案:

答案 0 :(得分:0)

您的要求应该更明确,例如是否需要全部加粗。实际上,您可以将单词与正则表达式匹配:

string stringToTest;
string patternToMatch = @"\bhello\b";

textDocument.GetText(TextGetOptions.None, out stringToTest);
Regex regex = new Regex(patternToMatch, RegexOptions.Compiled);
MatchCollection matches = regex.Matches(stringToTest);

并使用ITextDocument.GetRange(Int32, Int32) Method获取范围:

ITextRange textRange;
textRange = textDocument.GetRange(match.Index, match.Index + 5);

最后通过以下方式设置characterFormat:

textRange.CharacterFormat = textCharacterFormat;

以下是有关所有单词加粗的演示:

    private void Bold_Click(object sender, RoutedEventArgs e)
   {
    //I get the document from richEditBox.Document for my test, you can get yours
    ITextDocument textDocument = richEditBox.Document;
    ITextCharacterFormat textCharacterFormat = textDocument.GetDefaultCharacterFormat();
    textCharacterFormat.Bold = FormatEffect.On;

    string stringToTest;
    string patternToMatch = @"\bhello\b";
    ITextRange textRange;

    textDocument.GetText(TextGetOptions.None, out stringToTest);
    Regex regex = new Regex(patternToMatch, RegexOptions.Compiled);
    MatchCollection matches = regex.Matches(stringToTest);

    foreach (Match match in matches)
    {
        textRange = textDocument.GetRange(match.Index, match.Index + 5);
        textRange.CharacterFormat = textCharacterFormat;
    }
   }