简体   繁体   English

用于包含字母数字和特殊字符但不包含特殊字符的正则表达式

[英]Regex for including alphanumeric and special characters but not special characters on their own

Im trying to create some validation rules for a data member, but am having trouble with one of my regular expressions.我试图为数据成员创建一些验证规则,但是我的一个正则表达式遇到了问题。 Currently I am using @"[a-zA-Z']+$" as I want to allow strings such as:目前我正在使用@"[a-zA-Z']+$"因为我想允许字符串,例如:

  • John Smith (valid)约翰·史密斯(有效)
  • Steve Mc'millan (valid)史蒂夫麦克米兰(有效)
  • ''''' (invalid) ''''' (无效的)
  • Hill St' (valid) Hill St'(有效)

This works as expected, but when I try pass a string with just the special characters, it allows it.这按预期工作,但是当我尝试传递一个只包含特殊字符的字符串时,它允许它。 Is there a way where I can allow the special characters ' , but not allow it on its own?有没有办法可以允许特殊字符' ,但不允许它自己?

Here is my rule Im creating:这是我创建的规则:

        RuleFor(h => h.Name)
            .Cascade(CascadeMode.Stop)
            .NotEmpty().WithMessage("{PropertyName} is required")
            .Matches(@"[a-zA-Z']+$").WithMessage("{PropertyName} is invalid");

You can use您可以使用

RuleFor(h => h.Name)
    .Cascade(CascadeMode.Stop)
    .NotEmpty().WithMessage("{PropertyName} is required")
    .Matches(@"^(?!'+$)[a-zA-Z']+(?:\s+[a-zA-Z']+)*$").WithMessage("{PropertyName} is invalid");

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

  • ^ - matches the start of string position ^ - 匹配字符串 position 的开头
  • (?!'+$) - a negative lookahead that fails the match if there are one or more ' chars followed by the end of string position immediately to the right of the current (ie start of string) position. (?!'+$) - 如果有一个或多个'字符后跟紧跟当前(即字符串开头)position 右侧的字符串 position 的结尾,则匹配失败。
  • [a-zA-Z']+ - one or more letters or ' [a-zA-Z']+ - 一个或多个字母或'
  • (?:\s+[a-zA-Z']+)* - zero or more repetitions of (?:\s+[a-zA-Z']+)* - 零次或多次重复
    • \s+ - one or more whitespaces \s+ - 一个或多个空格
    • [a-zA-Z']+ - one or more letters or ' chars [a-zA-Z']+ - 一个或多个字母或'字符
  • $ - end of string. $ - 字符串结束。

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

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