C# Regular expression - exclude underscores & spaces at beginning and end of text

Viewed 91

I've been battling trying to get this regular expression to work. I want the expression to display the error when a string contains space either at beginning or at the end of a strong (spaces in the middle are allowed). Also I would like to exclude underscore and hyphens.

This is what I have so far.

[RegularExpression(@"^.*\s*[-_]", ErrorMessage = "string cannot begin with or end with a space, or contain a hyphen or underscore")]

This doesnt work as expected, anyone know what I am missing to get this to work?

1 Answers

You can use

[RegularExpression(@"^[^\s_-]+(?:\s+[^\s_-]+)*$", ErrorMessage = "string cannot begin with or end with a space, or contain a hyphen or underscore")]

Details

  • ^ - start of string
  • [^\s_-]+ - one or more chars other than whitespace, _ and -
  • (?:\s+[^\s_-]+)* - zero or more reptitions of:
    • \s+ - one or more whitespaces
    • [^\s_-]+ - one or more chars other than whitespace, _ and -
  • $ - end of string.

See the regex demo.

Related