Reputation: 1654
Why does this regular expression
/^[^-_]*([A-Za-z0-9]{3,})+[-_]?[^-_]*$/i
match on this String?
,abc,,.
It clearly says that the String should only contain of
The regex should not allow any other characters than A-z
, 0-9
and - or _
, but yet, it allows them.
Thanks in advance
Upvotes: 0
Views: 82
Reputation: 853
[^-_]*
is not "no - or _" but is "everything else than - or _" as every other part of your expression may be absent...
[^-_]*
make your Regexp matching the string.
Upvotes: 1
Reputation: 324620
Erm, actually, it clearly says:
-
or _
(matches ,
)abc
)-
or _
(matches nothing)-
or _
(matches ,,.
)Did you mean:
/^[a-z0-9]{3,}(?:[-_][12]+)?$/i
Correction, I misunderstood your "point 3".
/^[a-z0-9]{3,}(?:[-_][a-z0-9]{3,})*$/i
Upvotes: 5
Reputation: 71538
[^-_]*
will match the first comma, ([A-Za-z0-9]{3,})+
will match the abc
, [-_]?
will not match anything, [^-_]*
will match the last 2 commas and the dot.
Note that using the i
flag allows you to use ([A-Z0-9]{3,})+
or ([a-z0-9]{3,})+
just as well as your current regex.
If you want:
Then I would suggest:
/^(?:[a-z]{2}[-_]?)+[a-z]$/i
If by 'letters' you actually wanted letters and numbers, then I would suggest:
/^(?:[a-z0-9]{2}[-_]?)+[a-z0-9]$/i
Upvotes: 1
Reputation: 97672
[^-_]*
means 0 ore more characters that are not -
or _
, ,
and ,,.
satisfies that condition.
Upvotes: 1