开发者

How to find indices of groups in JavaScript regular expressions match? [duplicate]

开发者 https://www.devze.com 2022-12-15 00:29 出处:网络
This question already has answers here: 开发者_StackOverflow中文版 Get index of each capture in a JavaScript regex
This question already has answers here: 开发者_StackOverflow中文版 Get index of each capture in a JavaScript regex (7 answers) Closed last year.

When I write a regular expression like:

var m = /(s+).*?(l)[^l]*?(o+)/.exec("this is hello to you");
console.log(m);

I get a match object containing the following:

{
  0: "s is hello",
  1: "s",
  2: "l",
  3: "o",
  index: 3,
  input: "this is hello to you"
}

I know the index of the entire match from the index property, but I also need to know the start and end of the groups matched. Using a simple search won't work. In this example it will find the first 'l' instead of the one found in the group.

Is there any way to get the offset of a matched group?


You can't directly get the index of a match group. What you have to do is first put every character in a match group, even the ones you don't care about:

var m= /(s+)(.*?)(l)([^l]*?)(o+)/.exec('this is hello to you');

Now you've got the whole match in parts:

['s is hello', 's', ' is hel', 'l', '', 'o']

So you can add up the lengths of the strings before your group to get the offset from the match index to the group index:

function indexOfGroup(match, n) {
    var ix= match.index;
    for (var i= 1; i<n; i++)
        ix+= match[i].length;
    return ix;
}

console.log(indexOfGroup(m, 3)); // 11


I wrote a simple (well the initialization got a bit bloated) javascript object to solve this problem on a project I've been working on recently. It works the same way as the accepted answer but generates the new regexp and pulls out the data you requested automatically.

var exp = new MultiRegExp(/(firstBit\w+)this text is ignored(optionalBit)?/i);
var value = exp.exec("firstbitWithMorethis text is ignored");

value = {0: {index: 0, text: 'firstbitWithMore'},
         1: null};

Git Repo: My MultiRegExp. Hope this helps someone out there.

edit Aug, 2015:

Try me: MultiRegExp Live.


Another javascript class which is also able to parse nested groups is available under: https://github.com/valorize/MultiRegExp2

Usage:

let regex = /a(?: )bc(def(ghi)xyz)/g;
let regex2 = new MultiRegExp2(regex);

let matches = regex2.execForAllGroups('ababa bcdefghixyzXXXX'));

Will output:
[ { match: 'defghixyz', start: 8, end: 17 },
  { match: 'ghi', start: 11, end: 14 } ]


I have played around with adding nested capture groups and named groups with position information. You can play with some regex on jsfiddle... https://jsfiddle.net/smuchow1962/z5dj9gL0/

/*
Copyright (c) 2019 Steven A Muchow
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Enhanced RegEx JS processing
Adds position information for capture groups (nested ones too) AND named group items.
*/
class RegexContainer {

    static _findCaptureGroupsInRegexTemplate(re, input) {
        let refCount = 0; let matches = []; let res; let data;
        re.lastIndex = 0;
        while ((res = re.exec(input)) !== null) {
            if (isCapturingStartItem(res[0])) {
                refCount++;
                data = {parent: 0, refCount: refCount, start: res.index};
                if (res.groups.name) { data.name = res.groups.name; }
                matches.push(data);
            } else if (input.charAt(res.index) === ')') {
                let idx = matches.length;
                while (idx--) {
                    if (matches[idx].end === undefined) {
                        matches[idx].end = re.lastIndex;
                        matches[idx].source = input.substring(matches[idx].start, matches[idx].end);
                        break;
                    }
                }
                refCount--;
                let writeIdx = idx;
                while (idx--) {
                    if (matches[idx].refCount === refCount) {
                        matches[writeIdx].parent = idx + 1;
                        break;
                    }
                }
            }
        }
        matches.unshift({start: 0, end: input.length, source: input});
        return matches;

        function isCapturingStartItem(str) {
            if (str !== '(') { return (str.search(/\(\?<\w/)!==-1); }
            return true;
        }
    }

    static execFull(re, input, foundCaptureItems) {
        let result; let foundIdx; let groupName;  const matches = [];
        while ((result = re.exec(input)) !== null) {
            let array = createCustomResultArray(result);
            array.forEach((match, idx) => {
                if (!idx) {
                    match.startPos = match.endPos = result.index;
                    match.endPos += result[0].length;
                    delete match.parent;
                    return;
                }
                let parentStr = array[match.parent].data;
                foundIdx = (match.parent < idx - 1) ? parentStr.lastIndexOf(match.data) : parentStr.indexOf(match.data);
                match.startPos = match.endPos = foundIdx + array[match.parent].startPos;
                match.endPos += match.data.length;
                if ((groupName = foundCaptureItems[idx].name)) { match.groupName = groupName; }
            });
            matches.push(array);
            if (re.lastIndex === 0) { break; }
        }
        return matches;

        function createCustomResultArray(result) {
            let captureVar = 0;
            return Array.from(result, (data) => {
                return {data: data || '', parent: foundCaptureItems[captureVar++].parent,};
            });
        }
    }

    static mapCaptureAndNameGroups(inputRegexSourceString) {
        let REGEX_CAPTURE_GROUPS_ANALYZER = /((((?<!\\)|^)\((\?((<(?<name>\w+)))|(\?<=.*?\))|(\?<!.*?\))|(\?!.*?\))|(\?=.*?\)))?)|((?<!\\)\)(([*+?](\?)?))?|({\d+(,)?(\d+)?})))/gm;
        return RegexContainer._findCaptureGroupsInRegexTemplate(REGEX_CAPTURE_GROUPS_ANALYZER, inputRegexSourceString);
    }

    static exec(re, input) {
        let foundCaptureItems = RegexContainer.mapCaptureAndNameGroups(re.source);
        let res = RegexContainer.execFull(re, input, foundCaptureItems);
        return {captureItems: foundCaptureItems, results: res};
    }

}

let answers = [];
let regex = [
    { re: "[ \\t]*?\\[\\[(?<inner>\\s*(?<core>\\w(.|\\s)*?)\\s*?)]]", label: "NESTED Regex"},
  { re: "(?<context>((\\w)(\\w|-)*))((?<separator>( - ))?(?<type>(-|\\w)+)?\\s*(?<opt>(\\{.*}))?)?[\\t ]*", label: "simpler regex" },
]

let input = "[[ context1 ]]  [[ context2 - with-style { andOpts : {data: 'some info'} } ]]";

regex.forEach( (item) => {
    let re = new RegExp(item.re, 'gm');
  let result = RegexContainer.exec(re,input);
  result.label = item.label;
  answers.push(result);
});

answers.forEach((answer,index) => {
    console.log('==========================================================');
    console.log('==== Item ' + index + ' label: ' + answer.label + ' regex: ' + answer.captureItems[0].source );
    console.log('==========================================================\n\n');
    let scannedItems = answer.results;
    scannedItems.forEach( (match) => {
        let full = match[0];
        let mstr = full.data;
        let substr = input.substring(full.startPos, full.endPos);
        if (mstr !== substr) {
            console.log('error in the parsing if you get here');
            return;
        }
        console.log('==== Checking ' + mstr);
        for (let i=1; i<match.length; i++) {
            let capture = match[i];
            if (capture.groupName) {
                console.log(' ' + capture.groupName + ': ' + "```" + input.substring(capture.startPos,capture.endPos) + "```");
            }
        }
        console.log('');
    });
});

Architecture

  • Take Regex Template and identify the capture groups it will generate. Save it off as an array of group items and nesting info to feed into the expanded exec() call.
    • use regex to find capturing starts, non-capturing elements, capture names and capture endings. Trap properly for the dreaded \( and \) items.
    • non-recursive inspection of capture items and their parents (using reference counting).
  • run the exec() with the capture group information pulled above.
    • use substring functions to extract data for each capture group
    • put everything into an array for each result found and send the array back.


Based on the ecma regular expression syntax I've written a parser respective an extension of the RegExp class which solves besides this problem (full indexed exec method) as well other limitations of the JavaScript RegExp implementation for example: Group based search & replace. You can test and download the implementation here (is as well available as NPM module).

The implementation works as follows (small example):

//Retrieve content and position of: opening-, closing tags and body content for: non-nested html-tags.
var pattern = '(<([^ >]+)[^>]*>)([^<]*)(<\\/\\2>)';
var str = '<html><code class="html plain">first</code><div class="content">second</div></html>';
var regex = new Regex(pattern, 'g');
var result = regex.exec(str);

console.log(5 === result.length);
console.log('<code class="html plain">first</code>'=== result[0]);
console.log('<code class="html plain">'=== result[1]);
console.log('first'=== result[3]);
console.log('</code>'=== result[4]);
console.log(5=== result.index.length);
console.log(6=== result.index[0]);
console.log(6=== result.index[1]);
console.log(31=== result.index[3]);
console.log(36=== result.index[4]);

I tried as well the implementation from @velop but the implementation seems buggy for example it does not handle backreferences correctly e.g. "/a(?: )bc(def(\1ghi)xyz)/g" - when adding paranthesis in front then the backreference \1 needs to be incremented accordingly (which is not the case in his implementation).


For global regex you want to match only fragments and iterate so first solution won't work. This is a 30 min solution based on indexOf and sums that work for this case:

https://codepen.io/cancerberoSgx/pen/qYwjjz?editors=0012#code-area

!function () {
  const regex = /\/\*\*\*@\s*([^@]+)\s*(@\*\*\*\/)/gim
  const exampleThatMatch = `
    /***@
    debug.print('hello editor, simpleNode kind is ' +
    arg.simpleNode.getKindName())
    @***/

    const a = 1 //user

    /***@
    debug.print(arg.simpleNode.getParent().getKindName())
    @***/
    `
  const text = exampleThatMatch 
  function exec(r, s) {
    function indexOfGroup(match, n) {
      var ix = match.index;
      for (var i = 1; i < n; i++)
        ix += match[i].length;
      return ix;
    }
    let result
    let lastMatchIndex = 0
    const matches = []
    while ((result = regex.exec(text))) {
      const match = []
      lastMatchIndex = text.indexOf(result[0], lastMatchIndex)
      let relIndex = 0 
      for (let i = 1; i < result.length; i++) {
        relIndex = text.indexOf(result[i], relIndex)
        match.push({ value: result[i], start: relIndex, end: relIndex + result[i].length })
      }
      matches.push(match)
    }
    return matches
  }
  const groupsWithIndex = exec(regex, text)
  console.log({RESULT: groupsWithIndex })
  // now test - let's remove everything else but matched groups 
  let frag = '' , sep = '\n#######\n'
  groupsWithIndex.forEach(match => match.forEach(group => {
    frag += text.substring(group.start, group.end) + sep
  }))
  console.log('The following are only the matched groups usign the result and text.substring just to verify it works OK:', '\n'+sep)
  console.log(frag)
}()

And just in case here is the typescript:

https://codepen.io/cancerberoSgx/pen/yjrXxx?editors=0012

| Enjoy

0

精彩评论

暂无评论...
验证码 换一张
取 消