简体   繁体   English

如何编写一个允许空格和限制字符数的正则表达式?

[英]How can I write a regex that will allow space and limit number of characters?

I have some validation in my Model. 我的模型中有一些验证。 For the Society Name: 对于社团名称:

  1. Only Letters, Upper and Lower Case. 仅字母,大小写。
  2. No numbers. 没有数字
  3. Must allow for Camel Case 必须允许骆驼套
  4. Allow for Spaces between words. 在单词之间留出空格。
  5. Limited from 1-16 characters. 限制为1-16个字符。

Code: 码:

[Required(ErrorMessage = "Society Name is required.")]
    [StringLength(200, ErrorMessage = "The {0} has a maximum of {1} characters.")]
    [RegularExpression(@"^[A-Z][0-9]{16}$", ErrorMessage = "Society Name field requires 1-16 Alphabetical characters.")]
    [Display(Name = "Society Name *")]
    public string SocietyName { get; set; }

You should actually allow spaces and lowercase letters, right now, those patterns are not even present in your current regex. 您实际上应该允许使用空格和小写字母,现在,这些模式甚至不会出现在当前的正则表达式中。 Also, you used [0-9] that matches digits, although numbers should not be matched as per your requirements. 同样,您使用了[0-9]来匹配数字,尽管数字不应根据您的要求进行匹配。

To match lower- and uppercase letters or/and whitespace chars, you may use 要匹配大小写字母或/和空格字符,可以使用

^[A-Za-z\s]{1,16}$

See this regex demo . 请参阅此正则表达式演示

Details 细节

  • ^ - start of string ^ -字符串的开头
  • [A-Za-z\\s]{1,16} - 1 to 16 ASCII letters or/and whitespace chars [A-Za-z\\s]{1,16} -1至16个ASCII字母或/和空格字符
  • $ - end of string. $ -字符串结尾。

If you only want to allow 1 space between words, use 如果您只想在单词之间留出1个空格,请使用

^(?=.{1,16}$)[A-Za-z]+(?:\s[A-Za-z]+)*$

See this regex demo . 请参阅此正则表达式演示

Details 细节

  • ^ - start of string ^ -字符串的开头
  • (?=.{1,16}$) - the string length can be 1 to 16 (?=.{1,16}$) -字符串长度可以是1到16
  • [A-Za-z]+ - 1+ ASCII letters [A-Za-z]+ -1+个ASCII字母
  • (?:\\s[A-Za-z]+)* - zero or more repetitions of (?:\\s[A-Za-z]+)* -零个或多个重复
    • \\s - 1 whitespace \\s -1个空格
    • [A-Za-z]+ - 1+ ASCII letters [A-Za-z]+ -1+个ASCII字母
  • $ - end of string. $ -字符串结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM