0

I am not so good with regex, I need some help and I am stuck...

This is what I got:

EDITED: Now is working fine, take a look at...

http://jsfiddle.net/oscarj24/qrPHk/1/

This is what I need:

// First 4 numbers must be always 9908
// After the 4 first numbers must be a : as delimiter
// After the delimiter...
// - the allowed values are just numbers from 0-9
// - the min. length is 3
// - the max. length is infinite
// RESULT:
// - Valid: 9908:123 or 9908:123456...
// - Invalid: 9908:12 or 9908:xyz

Thanks.

Oscar Jara
  • 13,479
  • 10
  • 58
  • 90

3 Answers3

9
var regex = /^9908:\d{3,}$/;

will match exactly 9908: followed by 3 or more digits.

Mike Tangolics
  • 247
  • 1
  • 4
Alexander Corwin
  • 1,050
  • 6
  • 9
  • Thanks for your answer! I deleted the previous comment because Mike Tangolics (from the next post) make everything more clear and my mistake was not to use the shorthand javascript regex but now it works fine :-) – Oscar Jara Mar 08 '12 at 17:44
5

Alexander Corwin's answer should work fine. I just wanted to add some explanation to his response.

You don't need square brackets around the 9908 because square brackets mean that any of the characters in them are valid. So what your code was actually trying to do was match either a 9, 0 or 8. When you want to specify a literal string of characters, you can just write them out like he did.

Ignoring that however, the second problem I see is that you used the wrong quantifier syntax for specifying the length of the 9908 segment. You need to use curly braces to specify specific length ranges like the {3,} does in his code. Parentheses are simply used to create groups of sequences and back-references.

Additionally, when you aren't creating a RegExp object you should use the shorthand JavaScript regex syntax which is started and ended with a forward slash. You can also add a modifier after the ending slash which changes how the regex is executed. For example:

var re = /stackoverflow/g;

The 'g' means that it can match multiple times on the subject string. There are several other modifiers which you can find more info on here: http://www.regular-expressions.info/javascript.html

Your fixed line should look like this:

var regex = /^9908:\d{3,}$/;
Mike Tangolics
  • 247
  • 1
  • 4
  • This answer has been added to the [Stack Overflow Regular Expression FAQ](http://stackoverflow.com/a/22944075/2736496), under "Modifiers". – aliteralmind Apr 10 '14 at 00:54
1

Use this:

var match = /^9908:[0-9]{3,}$/.test("9908:123");
​alert(match);​
Kash
  • 7,813
  • 4
  • 26
  • 46
  • Nice try but Alexander Corwin's answered first :-) Also, it's better to use '\d' instead of '[0-9]' but thank you for your answer too. – Oscar Jara Mar 08 '12 at 17:53