Regex string match? Regex string match? javascript javascript

Regex string match?


If you want the literal strings abc or def followed by 8-11 digits, you need something like:

(abc|def)[0-9]{8,11}

You can test it here: http://www.regular-expressions.info/javascriptexample.html

Be aware that, if you don't want to match more than 11 digits, you will require an anchor (or [^0-9]) at the end of the string. If it's just 8 or more, you can replace {8,11} with {8}.


To elaborate on an already posted answer, you need a global match, as follows:

var matches = string.match(/(abc|def)\d{8,11}/g);

This will match all subsets of the string which:

  • Start with "abc" or "def". This is the "(abc|def)" portion
  • Are then followed by 8-11 digits. This is the "\d{8,11}" portion. \d matches digits.

The "g" flag (global) gets you a list of all matches, rather than just the first one.

In your question, you asked for 8-11 characters rather than digits. If it doesn't matter whether they are digits or other characters, you can use "." instead of "\d".

I also notice that each of your example matches have more than 11 characters following the "abc" or "def". If any number of digits will do, then the following regex's may be better suited:

  • Any number of digits - var matches = string.match(/(abc|def)\d*/g);
  • At least one digit - var matches = string.match(/(abc|def)\d+/g);
  • At least 8 digits - var matches = string.match(/(abc|def)\d{8,}/g);


You can match abc[0-9]{8} for the string abc followed by 8 digits.

If the first three characters are arbitrary, and 8-11 digits after that, try [a-z]{3}[0-9]{8,11}