Reputation: 1594
I need to form a regular expression (reg ex) for an .aspx program that validates one character followed by optional characters.
The first character is more strict, not allowing hyphen or space.
I had
^[A-Za-z0-9][A-Za-z0-9 -]{1,9}
which works, except there must be at least two characters (the limit is 9 chars total).
The .net code was as follows:
controltovalidate="txt1" validationexpression="^[A-Za-z0-9][A-Za-z0-9 -]{1,9}"></ASP:REGULAREXPRESSIONVALIDATOR>
[Since asking the question, I've found that simply changing {1,9} to {0,9} accomplishes what I need, but I am retaining the question as possibly useful to others, especially the answer below]
I read that
^[A-Za-z0-9]([A-Za-z0-9 -])?{1,9}
might work as I'm grouping the chars after the first with parens and using a "?" as optional.
However, I really need to know if this is correct syntax before I move this code to production.
Furthermore, it fails an online reg expression validator.
Does anyone know if this will work for an aspx reg expression validator?
Upvotes: 1
Views: 101
Reputation: 1884
Try the following: /^[A-Za-z0-9](?:[A-Za-z0-9 -]){1,8}$/
Working Demo @ regex101
In your pattern ^[A-Za-z0-9]([A-Za-z0-9 -])?{1,9}
the greedy quantifier aka {n,m}
is preceded by the greedy quantifier aka ?
, none of them are quantifiable tokens, So having a quantifier token preceded by another quantifier token is sematically incorrect.
In order to achieve your goal you must let that your second range of acceptable characters only allow 1 to 8 appearances: (?:[A-Za-z0-9 -]){1,8}
Upvotes: 1