如何获取不匹配的字符?

时间:2019-05-01 15:21:26

标签: c# regex

在C#中,我有以下正则表达式可以测试有效的用户名:

public const string ValidUserNamePattern = @"^(?=.{5,53}$)([\p{L}\w][.!_-]?)*$";

这应该接受长度在5到53个字符之间的字符串,所有字符包括变音符号和特殊符号“。”,“!”,“ _”,“-”。

如果有人输入d'Agostinivan den Helde之类的名称,我们将使用无效字符(空格和')。如何只打印无效字符?

public const string ValidUserNamePattern = @"^(?=.{5,53}$)([\p{L}\w][.!_-]?)*$";

var validString = "TestUsrNèüäme";
var invalidString = "Te st|^us r";
var validUserNameRegEx = new Regex(OpManConstants.ValidUserNamePattern, RegexOptions.Compiled);

if (!validUserNameRegEx.IsMatch(invalidString))
{
    // How to get NOT MATCHING character or in other words
    // how to get all characters causing the Regex NOT to match?
}

有什么想法可以在C#中完成吗?

2 个答案:

答案 0 :(得分:1)

您可以做的是先使用否定的字符类并使用\p{L}检查/匹配字符串是否包含无效字符,然后添加您允许的字符.!_-

[^\p{L}.!_-]

Regex demo | C# demo

答案 1 :(得分:0)

正如我在评论中所说,一种解决方案是找到与有效字符不匹配的任何字符。
您的“正确字符正则表达式”为$mailgun = Mailgun::create(config('mail.mailgunSecret')); $result = $mailgun->sendMessage(config('mail.mailgunDomain'), [ 'from' => config('mail.from'), 'to' => $emails, 'subject' => '%recipient.first% no te pierdas lo último de '.config('app.name'), 'html' => $html, 'recipient-variables' => '{ "example@gmail.com": {"first":"Gabriel", "id":1}, "example@gmail.com": {"first":"Silvia", "id":2} }' ]); ,因此您的“不正确字符正则表达式”为[\p{L}\w.!_-]

[^\p{L}\w.!_-]

输出为:

protected const string ValidUserNameCharacters = @"\p{L}\w.!_-";

public const string ValidUserNamePattern = @"^(?=.{5,53}$)([" + ValidUserNameCharacters + @"]?)*$";
public const string InvalidUserNamePattern = @"([^" + ValidUserNameCharacters + "])";

var invalidString = "Te st|^us r";
var validUserNameRegEx = new Regex(OpManConstants.ValidUserNamePattern, RegexOptions.Compiled);
var invalidUserNameRegEx = new Regex(OpManConstants.InvalidUserNamePattern, RegexOptions.Compiled);

if (!validUserNameRegEx.IsMatch(invalidString))
{
    var matches = invalidUserNameRegEx.Matches(invalidString);
    var builder = new StringBuilder();
    foreach (var match in matches.Cast<Match>())
    {
        builder.AppendLine("'" + match.Groups[0] + "' at char " + (match.Index + 1));
    }

    Console.WriteLine(builder.ToString());
}