8

I want to find /AA/ pattern in AA-AA-AA subject string. I need to get the matching string and the position (index) of the match.

I have looked at RegExp.prototype.exec(). It only returns the first match:

/AA/g.exec('AA-AA-AA')
3
  • 4
    Introducing jsfiddle.net - a place you can go for all your HTML/CSS/JS demoing needs.
    – BoltClock
    May 30, 2011 at 15:52
  • is that you want ? rubular.com/r/X9NQ4h1xYH
    – xkeshav
    May 30, 2011 at 15:56
  • not really. my problem is not writing the pattern, but getting the information i need after search was performed - the index values of the results to be exact
    – yotamoo
    May 30, 2011 at 15:58

4 Answers 4

19

exec() only returns a single match. To get all matches with a g​lobal regexp, you have to call it repeatedly, eg.:

var match, indexes= [];
while (match= r.exec(value))
    indexes.push([match.index, match.index+match[0].length]);
5
  • Great. Made me that much wiser
    – mplungjan
    May 30, 2011 at 16:15
  • 1
    Why not use str.match(regex) instead of regex.exec(str)?
    – Rudie
    May 30, 2011 at 16:19
  • match() only gives you the matching strings, exec gives you match objects with more information available on them (the matching string can be accessed from them as [0]). If you want the indexes, you need exec.
    – bobince
    May 30, 2011 at 16:26
  • 2
    @bobince that's not true. Assuming the regex being used is not global, String.prototype.match and RegExp.prototype.exec return the same thing. Tested in chrome, firefox, and ie. Also Ecma-262 suggests that match should use exec internally: bclary.com/2004/11/07/#a-15.5.4.10
    – Xavi
    May 12, 2012 at 15:54
  • 2
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… if the regular expressioin does not include the g flag, str.match() will return the same result as RegExp.exec() If includes the g flag, str.match() returns an Array containing all matched substrings rather than match objects, Captured groups are not returned
    – jk2K
    Sep 21, 2018 at 15:20
3

Be careful when using RegExp.prototype.exec() function to match a string. The constructed regex object is stateful, i.e. every time you call .exec() it affects the lastIndex property of the regex instance. Therefore, you should always reset the lastIndex property before using an instance of regex object.

let re,
    findAAs;

re = /AA/;

findAAs = (input) => {
    let match;

    // `re` is cached instance of regex object.
    // Reset `re.lastIndex` every time before using it.

    re.lastIndex = 0;

    while ((match = re.exec(input)) !== null) {
        match.index; // Match index.
        match[0]; // Matching string.
    }
};

A tempting alternative is to construct the regex object on every execution. Depending on how resource intensive your task is, this is an option too.

let findAAs;

findAAs = (input) => {
    let match,
        re;

    re = /AA/;

    while ((match = re.exec(input)) !== null) {
        match.index; // Match index.
        match[0]; // Matching string.
    }
};

A pragmatic alternative to using .exec() is String.prototype.replace().

let findAAs,
    re;

re = /AA/;

findAAs = (input) => {
    let match,
        re;

    input.replace(re, (match, index) => {
        match; // Matching string.
        index; // Match index.

        return '';
    });
};

The downside of this approach is that it constructs a copy of the subject string.

Whether you should use it or not, depends on how resource intensive your task is. Personally, I like to avoid while blocks in my code and therefore prefer the .replace() approach.

1
  • > The constructed regex object is stateful. .... This is true only if you pass g flag to regex.
    – Oleh Devua
    Jul 11, 2017 at 10:56
0

http://jsfiddle.net/mplungjan/MNXvQ/

I think this is easier to grasp

var str = "AAbAAcAAd"
var re = /(AA)/gi;
var t="",cnt=0;
while ((result=re.exec(str))!=null) {
    document.write((cnt++)+":"+result[1]+"<br />")        
}

re.lastIndex contains the positions each time

0

An alternative to bobince's answer is to use the 'lastIndex' property of the regex to get the end index of each match

var match, indexes= [];
while (match = r.exec(value)) {
    indexes.push([match.index, r.lastIndex]);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.