在 RichTextBox WPF MVVM 中突出显示电子邮件和 phone 号码

Highlight Email And phone Number In RichTextBox WPF MVVM

你好,我在 C# Wpf 应用程序中有一个 RichTextBox,我想制作一个控件来突出显示电子邮件和 phone 号 OnPreviewMouseMove 事件 我如何检测电子邮件地址并突出显示它?

您可以使用它来突出显示电子邮件:

string data = richTextBox1.Text;

Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
RegexOptions.IgnoreCase);
//find items that matches with our pattern
MatchCollection emailMatches = emailRegex.Matches(data);
foreach (Match item in emailMatches)
{
    var index = item.Index;
    var length = item.Length;

    richTextBox1.Select(index, length);
    richTextBox1.SelectionBackColor = Color.Yellow;
}

并且您可以根据要检测的 phone 数字的格式对 phone 使用相同的代码和不同的正则表达式。我必须澄清,我使用的正则表达式模式可能无法涵盖所有​​类型的电子邮件!因此,虽然代码是合适的,但您需要为您的情况找到一个正则表达式模式。