I_Debug_Everything
I_Debug_Everything

Reputation: 3816

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 

i.e 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.

Upvotes: 2

Views: 187

Answers (3)

anubhava
anubhava

Reputation: 785008

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"]

Upvotes: 5

vinayakj
vinayakj

Reputation: 5681

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[b-z]*a/g); // notice the regular expression is changed.

alert(substrs)

Upvotes: 1

Ionic
Ionic

Reputation: 3935

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

Upvotes: 0

Related Questions