Regex string match?

87,585

Solution 1

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

Solution 2

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);

Solution 3

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}

Solution 4

Use the below regex to get the exact match,

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

Ends with g

"g" for global

"i" for ignoreCase

"m" for multiline

Share:
87,585

Related videos on Youtube

Andy
Author by

Andy

Updated on July 09, 2022

Comments

  • Andy
    Andy almost 2 years

    I have a long string in javascript like

    var string = 'abc234832748374asdf7943278934haskhjd';

    I am trying to match like

    abc234832748374 - that is - I have tried like

    string.match(\abc[^abc]|\def[^def]|) but that doesnt get me both strings because I need numbers after them ?

    Basically I need abc + 8 chars after and def the 8-11 chars after ? How can I do this ?