简体   繁体   中英

Javascript regular expression - matching multiple occurrences

I'm a little stuck on a problem here. I'm trying to match multiple occurrences of a regular expression in a string, but I don't get all occurrences:

Sample:

      s = new RegExp(';' + y[p][0] + '_' + y[p][1] + '_' + y[p][2] + '_([0-9]*);', 'g');
        e = null;
        e = s.exec(grArr);
        while (e != null) {
            alert(e[0]+'-'+e[1]+'-'+e[2]); //debugging output
            r = r + e[0]; //adding results to output var
            e = s.exec(grArr);
        }

Sample variables:
//to be searched:
var grArr=';0_0_709711498101583267971121121179999105110111_11994876;0_0_709711498101583267971121121179999105110111_11994877;0_0_709711498101583267971121121179999105110111_11994878;0_0_709711498101583267971121121179999105110111_11994879;0_0_709711498101583268117110107101108103114252110_11994872;0_0_709711498101583268117110107101108103114252110_11994873;0_0_709711498101583268117110107101108103114252110_11994874;0_0_709711498101583268117110107101108103114252110_11994875;0_0_7097114981015832839910411997114122_11994868;0_0_7097114981015832839910411997114122_11994869;0_0_7097114981015832839910411997114122_11994870;0_0_7097114981015832839910411997114122_11994871;0_1_71114246115115101583276_11994870;0_1_71114246115115101583276_11994874;0_1_71114246115115101583276_11994878;0_1_71114246115115101583277_11994869;0_1_71114246115115101583277_11994873;0_1_71114246115115101583277_11994877;0_1_71114246115115101583283_11994868;0_1_71114246115115101583283_11994872;0_1_71114246115115101583283_11994876;0_1_7111424611511510158328876_11994871;0_1_7111424611511510158328876_11994875;0_1_7111424611511510158328876_11994879;'
//search Pattern:
y[0][0]='0';
y[0][1]='1';
y[0][2]='71114246115115101583283';

This results in 2 occurrences - not 3 as it should be.

The problem is that you're using the semicolon twice: Once at the start of the regex, once at the end.

Since in your example the three "matches" directly follow each other, the second occurrence is not found because its preceding semicolon has already been used in the previous match.

Solution: Use word boundaries ( '\\\\b' ) instead of ';' in your regex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM