Reputation: 38209
The row should be:
.
and minus sign -
I've written the following Regex
pattern:
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?
Upvotes: 1
Views: 3734
Reputation: 627537
You can use
string pattern = @"^[A-Za-z][A-Za-z0-9.-]{0,19}(?<=[A-Za-z0-9])$";
or a bit more enhanced as it will fail quicker with non-matching input and won't allow any trailing newlines ever:
string pattern= @"^[A-Za-z][A-Za-z0-9.-]{0,19}\z(?<=[A-Za-z0-9])";
Details:
^
- 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)Upvotes: 2
Reputation: 2425
Try something like this:
^[A-Za-z]([-.A-Za-z0-9]{0,18}[A-Za-z0-9])?$
It will begin by matching a single alphabetic character, and then optionally a series of up to 18 letters, numbers, periods, or hyphens, terminated by an alphanumeric. You can escape the hyphen in the character class if you wish, but if you don't you should make it the first character in the class so that it isn't interpreted as a range. Making the hyphen the last character in the class works for some implementations.
https://regex101.com/r/fA8lQ4/3
Upvotes: 1