StepUp StepUp - 1 month ago 6x
C# Question

Set limit to length of Regular expression

The row should be:

  • start from latinic letter

  • consist from latinic letters, numbers, dot sign
    and minus sign

  • the string should end with an alphanumeric

  • min length of row is 1

  • max length of row is 20

I've written the following

string pattern = @"^[A-Za-z]{1}[A-Za-z0-9\-\.]{1,18}[A-Za-z0-9]{1}$";

and the third, fourth and fiveth conditions are not satisfied:

string s1 = "E";

// Compare a string against the regular expression
var isOK = new Regex(pattern).IsMatch(s1);

Could you tell me the right way to create a Regex pattern?


You can use

string pattern = @"^[A-Za-z][A-Za-z0-9.-]{0,19}(?<=[A-Za-z0-9])$";


  • ^ - start of string
  • [A-Za-z] - a letter
  • [A-Za-z0-9.-]{0,19} - 0 to 19 letters, digits or . or - symbols
  • (?<=[A-Za-z0-9]) - there should be an alphanumeric before....
  • $ - the end of the string (better replace with \z to match the very end of the string)