Reputation: 93
var re = /^\[*:*\]*/;
alert(re.test("aa"));
Always alerts true (on any string). What am i doing wrong? I need to check is there something like [445:123] in the beginning of the string.
Upvotes: 1
Views: 480
Reputation: 414016
Your regex means
[
characters ...:
characters ...]
characters.The string "aa" matches that. You probably want something like:
var re = /^\[\d+:\d+\]/;
The +
quantifier means "one or more", while *
means "zero or more". The \d
escape means "any digit".
*edit — if the regex needs to match something like
[12:2:17:419]
as well, then it would be
var re = /^\[\d+(:\d+)+\]/;
Upvotes: 5
Reputation: 58619
in regular expressions, *
does not mean wildcard match, it means zero or more of the previous token. To match any character, use .
instead. A regex for what you want to match is more like this...
/^\[.*:.*\].*/
But better is to be more specific, using \d
to match decimals, and use +
to match one or more of the previous token, and remove the erroneous characters after the match...
/^\[\d+:\d+\]/
Upvotes: 0
Reputation: 1553
You're checking for any number of [
, followed by any number of :
, followed by any number of ]
. Note that that's any number - 0 occurrences of any of those is a valid result.
What it sounds like you mean to do is something more like var re= /^\[\d+:\d+\]/;
Upvotes: 1