XAML 如何从UWP中的RichEditBox中提取所有具有链接的范围和链接内容

ws51t4hk  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(208)

想象一下,我有一个RichEditBox字符串长度为100,并且有10个链接设置为字符串中的不同集合,现在如何提取这10个链接的所有范围和链接的内容。我以这种方式设置了RichEditBox的链接

RichEditBox.TextDocument.Selection.StartPosition = 10;
RichEditBox.TextDocument.Selection.EndPosition = 16;
RichEditBox.TextDocument.Selection.Link = "\"www.google.com\"";
knpiaxh1

knpiaxh11#

这里有一个解决方案,使用TextGetOptions.FormatRtf获取Rtf格式的文本内容。
Text -->“This is so me sam ple text”,其Rtf格式如下。
{\f1\fbidis\ansi\ansicpg1252\def0\nouicompat\defang1033 {\fonttbl{\f0\fnil Segoe UI Variable;}}\r\n{\colortbl ;\red0\green0\blue0;\red0\green0\blue255;{*\generator Riched20 10.0.22621}\viewkind4\uc1 \r\n\pard\tx720\cf1\f0\fs21这是{{\field{*\fldinst{HYPERLINK“www.google.com“}}{\fldrslt{\ul\cf2 me sam}}}}\f0\fs21 ple text\par\r\n}\r\n\0
然后使用正则表达式(?<={HYPERLINK).*?(?=})(?<=cf2).*?(?=})获取链接和链接内容。

public MainPage()
    {
        this.InitializeComponent();
       
        richEditBox.Document.SetText(Windows.UI.Text.TextSetOptions.None, "This is some sample text");
        richEditBox.TextDocument.Selection.StartPosition = 10;
        richEditBox.TextDocument.Selection.EndPosition = 16;
        richEditBox.TextDocument.Selection.Link = "\"www.google.com\"";
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        string TextString = null;
        richEditBox.Document.GetText(Windows.UI.Text.TextGetOptions.FormatRtf, out TextString);

        string pattern = @"(?<={HYPERLINK).*?(?=})";
        string input = TextString;

        int count=0;

        foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
        {
           
            Debug.WriteLine("Link{0}: {1}",
                             ++count, match.Value.Trim());
        }

        
        count = 0;
        pattern = @"(?<=cf2).*?(?=})";

        richEditBox.Document.GetText(Windows.UI.Text.TextGetOptions.NoHidden, out TextString);
       
        int searchStart = 0;
        int searchLength = TextString.Length;

        foreach (Match match in Regex.Matches(input, pattern, RegexOptions.IgnoreCase))
        {

            Debug.WriteLine("Link Content{0}: {1} ",
                             ++count, match.Value.Trim());

            var searchText= TextString.Substring(searchStart, searchLength);

            pattern = @"("+match.Value.Trim()+")";
            foreach (Match posRes in Regex.Matches(searchText, pattern, RegexOptions.IgnoreCase))
            {
                Debug.WriteLine("startPos:{0} - endPos:{1} ",
                             posRes.Index, posRes.Index + match.Value.Trim().Length);
                searchStart = posRes.Index + match.Value.Trim().Length;
                searchLength = TextString.Length - posRes.Index - match.Value.Trim().Length;

            }
                
        }

    }

相关问题