在C#中,我有以下正则表达式可以测试有效的用户名:
public const string ValidUserNamePattern = @"^(?=.{5,53}$)([\p{L}\w][.!_-]?)*$";
这应该接受长度在5到53个字符之间的字符串,所有字符包括变音符号和特殊符号“。”,“!”,“ _”,“-”。
如果有人输入d'Agostini
或van 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#中完成吗?
答案 0 :(得分:1)
答案 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());
}