Using regex only to get a string with 7 digits

In short, the page contains about 10 divs, each of which contains letters and numbers, and I'm trying to return all occurrences to exactly 7 digits, but may have other, obscure characters before and after.

eg.

"q1234567" should return 1234567

"q1234567q" should return 1234567

"q1234567q1234567q12345678q" should return 1234567 and 1234567

"12345678" MUST NOT be returned

To be more specific, an example of an entire line:

q1234567q
q1234567q
q12345678q
q1234567q123456789q123456q1324567q1234567
1234567
1
12
123
1234
12345
q12345q
q1234
12345q
123

I tried to do this with regex and got to

/\d{7}(?=\D|$)/g

but JavaScript doesn't work very well with lookbehind. How can I get around this without bringing in a whole new library?

+3
source share
5 answers

, - ?

var regex = /(?:^|\D)(\d{7})(?!\d)/g;
var s = "q1234567q123456789q123456q1324567q1234567";
var match, matches=[];

while ( (match=regex.exec(s)) !== null ) {
    matches.push(match[1]);
}

alert(matches);

jsfiddle demo

+2

:

/^\D*\d{7}\D*$/

-: http://regex101.com/r/nE5eI6

:. :

(?:^|\D)(\d{7})(?=\D|$)

# 1 .

: http://regex101.com/r/wL4oW1

+4

How about (?<=\D)[0-9]{7}(?=\D|$)|^[0-9]{7}(?=\D|$):?

0
source
var regex = /(\b|\D)(\d{7})(\b|\D)/g
function get7digits(s) {
    var md, matches=[];
    while( (md=regex.exec(s)) !== null ) matches.push(md[2]);
    return matches;
}

get7digits('q1234567q123456789q123456q1324567q1234567')

["1234567", "1324567"]

0
source

How about this:

/(^|\D)\d{7}(\$|\D)/gm

http://regex101.com/r/iT5cR3

0
source

All Articles