Home > Enterprise >  Regular expression to find 9 consecutive numbers only in long string
Regular expression to find 9 consecutive numbers only in long string

Time:07-20

I have a very long string that I want to extract only numbers that are of 9 digits using regex. I'm getting now this:

var string = "This is a testingstringof differentchars%#$@f234 and numbers123456789 and it is very long902134756.....end"
var pattern = /\d /g;

const digitArray = string.match(pattern);

console.log(digitArray);

The output I get is this, as am just getting the numbers in this regex:

['234', '123456789', '902134756']

what I want to achieve is this :

['123456789', '902134756']

I also tried the following patterns from several threads but all give me null:

var pattern = ^\d{0,9}$
var pattern = /^\d{9}(?:\d{2})?$/
var pattern = \b\d{9}\b
var pattern = /^\d{9}$/

can you please guide me on what to use? Thanks.

CodePudding user response:

You're close. Looks like you want to add a length constraint on the digits. If you want nine digits in a row you can use:

/\d{9}/g

However this will also match the first nine digits in a ten digit number. From the wording of your question and the word boundary characters (\b) in other regexp attempts, I'm thinking you want exactly nine digits and no more, you can get this with:

/(^|\D)\d{9}(\D|$)/g

This will look for nine digits exactly. The (^|\D) looks for either the start of the line/string or a non-digit character and the (\D|$) similarly looks for the end of the line/string or a non-digit character. In other words, nine digits surrounded by non-digits.


Edit: As Amadan pointed out in the comments, this regular expression will also capture the character before and after the digits (as long as they aren't the beginning/end of the string).

The simplest way I can think to handle this is by using a capturing group on the digits and grabbing that group after matching, like so:

let string = "This is a testingstringof differentchars%#$@f234 and numbers123456789 and it is very long902134756.....end";
let pattern = /(^|\D)(\d{9})(\D|$)/g;

let match = [];
let nums = [];
while (match = pattern.exec(string)) {
    nums.push(match[2]);
}

Result for nums:

[ '123456789', '902134756' ]

See this answer on using subgroups in global regular expressions.

Or you can use Amadan's comment, both work.

CodePudding user response:

This works perfectly.

var string = "This is a testingstringof differentchars%#$@f234 and numbers123456789 and it is very long902134756.....end"
var pattern = /(^|\D)\d{9}($|\D)/g; // <--- number in the braces mean the no of digits you want

const digitArray = string.match(pattern);

console.log(digitArray);

This means that you want numbers that are 9 digits long.

  • Related