简体   繁体   中英

Counting all the occurrences of a substing in a string using regular expression

I've seen many examples of this but didn't helped. I have the following string:

var str = 'asfasdfasda'

and I want to extract the following

asfa asfasdfa asdfa asdfasda asda 

ie all sub-strings starting with 'a' and ending with 'a'

here is my regular expression

/a+[a-z]*a+/g

but this always returns me only one match:

[ 'asdfasdfsdfa' ]

Someone can point out mistake in my implementation.

Thanks.

Edit Corrected no of substrings needed. Please note that overlapping and duplicate substring are required as well.

For capturing overlapping matches you will need to lookahead regex and grab the captured group #1 and #2:

/(?=(a.*?a))(?=(a.*a))/gi

RegEx Demo

Explanation:

(?=...) is called a lookahead which is a zero-width assertion like anchors or word boundary. It just looks ahead but doesn't move the regex pointer ahead thus giving us the ability to grab overlapping matches in groups.

See more on look arounds


Code:

var re = /(?=(a.*?a))(?=(a.*a))/gi;
var str = 'asfasdfasda';
var m; 
var result = {};
while ((m = re.exec(str)) !== null) {
    if (m.index === re.lastIndex)
        re.lastIndex++;
    result[m[1]]=1;
    result[m[2]]=1;
}

console.log(Object.keys(result));
//=> ["asfa", "asfasdfasda", "asdfa", "asdfasda", "asda"]

parser doesnt goto previous state on tape to match the start a again.

 var str = 'asfaasdfaasda'; // you need to have extra 'a' to mark the start of next string var substrs = str.match(/a[bz]*a/g); // notice the regular expression is changed. alert(substrs) 

You can count it this way:

var str = "asfasdfasda";
var regex = /a+[a-z]*a+/g, result, indices = [];
while ((result = regex.exec(str))) {
     console.log(result.index); // you can instead count the values here.
}

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