[英]C#: Regex for name with 2 and/or 3 words
In my C# app, user enters a name. 在我的C#app中,用户输入一个名称。 I want to set a Regex where user can enter only 2 or 3 words ie "John Brandy" or "John Brandy Paul".
我想设置一个正则表达式,用户只能输入2或3个单词,即“John Brandy”或“John Brandy Paul”。 And each word not less than 2 and greater than 15 chars.
每个字不少于2个,大于15个字符。
Match match = Regex.Match(str, @"^[A-Z]+ [A-Z]+ [A-Z]+$", RegexOptions.IgnoreCase); // @"^\b[a-zA-Z]{2,15}\s[a-zA-Z]{2,15}\b"); //@"(\w)\s(\w){2, 3}");
Console.WriteLine("PAttern Success = " + match.Success);
With the current pattern, I got to enter 3 words. 按照目前的模式,我得输入3个单词。
Another idea to use a quantified group . 使用量化 组的另一个想法。
^(?:[A-Z]{2,15} ?\b){2,3}$
RegexOptions.IgnoreCase
RegexOptions.IgnoreCase
\\b
stands for word boundary . \\b
代表单词边界 。 You can use the ?
你可以使用
?
to match zero and once, along with the pattern in your comment. 匹配零和一次,以及评论中的模式。
^[a-zA-Z]{2,15}\s[a-zA-Z]{2,15}(?:\s[a-zA-Z]{2,15})?$
Additionally the ?:
tells that it should be a non-capturing group. 另外,
?:
告诉它应该是一个非捕获组。
Note that \\s
also matches newlines, so you might instead want [ \\t]
. 请注意
\\s
也匹配换行符,因此您可能需要[ \\t]
。 If you want to allow multiple spaces then use [ \\t]+
. 如果要允许多个空格,请使用
[ \\t]+
。
试试这个它应该工作。
^[a-zA-Z]{2,15}\\s([a-zA-Z]{2,15}\\s)?[a-zA-Z]{2,15}$
^(?:[AZ][A-Za-z]{2,15} ?\\b){2,3}$
无需使用IgnoreCase即可工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.