Sebastian
Sebastian

Reputation: 1654

JavaScript Regular Expressions Special Characters

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

  1. Minimum 3 letters
  2. Followed by an optional - or _
  3. Sequence of number 1 and 2 can be repeated infinite times
  4. No - or _ at the beginning or end of the String

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

Answers (4)

blobmaster
blobmaster

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

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Erm, actually, it clearly says:

  • From the start,
  • Any number of characters that are not - or _ (matches ,)
  • Catastrophically backtrack to find at least three alphanumerics (matches abc)
  • Optionally match a - or _ (matches nothing)
  • Any number of characters that are not - or _ (matches ,,.)
  • To the end.

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

Jerry
Jerry

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:

  1. Minimum 3 letters
  2. Followed by an optional - or _
  3. Sequence of number 1 and 2 can be repeated infinite times
  4. No - or _ at the beginning or end of the String

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

Musa
Musa

Reputation: 97672

[^-_]* means 0 ore more characters that are not - or _, , and ,,. satisfies that condition.

Upvotes: 1

Related Questions