小编Suz*_*uzy的帖子

正则表达式使用相同字符串模式属性的变量 C#

我们可以替换字符串模式@"^[a-zA-Z''-'\s]{1,40}$"以用作属性中的变量吗?

我尝试将模式设置为字符串,但是当我使用[RegularExpression...]变量时它不起作用。我想使用一个变量,因为它是相同的正则表达式格式。

  private static String regexFormat = @"^[a-zA-Z''-'\s]{1,40}$";
Run Code Online (Sandbox Code Playgroud)

或者

   private static String regexFormat = "^[a-zA-Z''-'\s]{1,40}$";

  
    [Display(Name = "Name", Description = "First Name + Last Name.")]
    [Required(ErrorMessage = "First Name is required.")]
    [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage =
        "Numbers and special characters are not allowed in the name.")]


    [Required(ErrorMessage = "Last Name is required.")]
    [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$", ErrorMessage =
        "Numbers and special characters are not allowed in the name.")]
Run Code Online (Sandbox Code Playgroud)

我想要这样的东西

[RegularExpression(regexFormat, ErrorMessage ="Error in Format")]
Run Code Online (Sandbox Code Playgroud)

这可能吗,如果可以的话怎么办?

.net c# regex string

6
推荐指数
1
解决办法
157
查看次数

标签 统计

.net ×1

c# ×1

regex ×1

string ×1