1
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.

1
  • Your regex means "Start of string, then zero of more [ then zero or more :, then zero of more ] . aa does contains 0 or more of the above. What are you trying to test here? Commented Oct 22, 2013 at 0:02

3 Answers 3

5

Your regex means

  • at the start of the string ...
  • there can be zero or more [ characters ...
  • then zero or more : characters ...
  • then zero or more ] 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+)+\]/;
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! Can you give an advice how to build a correct regex?
What the OP could use /^\[\d*:\d*\]/
@Pointy unfortunatelly, there can be any number (but at least two) of \d: groups. Is there any way to solve this?
@user32876 sure; you can group the ":" and the second number. I'll add stuff. Here's a decent website about regular expressions.
@Pointy last regex worked fine. Thank you very much!
1

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+\]/;

Comments

0

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+\]/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.