Named capturing groups in JavaScript regex?

2019-01-03 02:39发布

As far as I know there is no such thing as named capturing groups in JavaScript. What is the alternative way to get similar functionality?

8条回答
虎瘦雄心在
2楼-- · 2019-01-03 03:10

While you can't do this with vanilla JavaScript, maybe you can use some Array.prototype function like Array.prototype.reduce to turn indexed matches into named ones using some magic.

Obviously, the following solution will need that matches occur in order:

// @text Contains the text to match
// @regex A regular expression object (f.e. /.+/)
// @matchNames An array of literal strings where each item
//             is the name of each group
function namedRegexMatch(text, regex, matchNames) {
  var matches = regex.exec(text);

  return matches.reduce(function(result, match, index) {
    if (index > 0)
      // This substraction is required because we count 
      // match indexes from 1, because 0 is the entire matched string
      result[matchNames[index - 1]] = match;

    return result;
  }, {});
}

var myString = "Hello Alex, I am John";

var namedMatches = namedRegexMatch(
  myString,
  /Hello ([a-z]+), I am ([a-z]+)/i, 
  ["firstPersonName", "secondPersonName"]
);

alert(JSON.stringify(namedMatches));

查看更多
戒情不戒烟
3楼-- · 2019-01-03 03:13

You can use XRegExp, an augmented, extensible, cross-browser implementation of regular expressions, including support for additional syntax, flags, and methods:

  • Adds new regex and replacement text syntax, including comprehensive support for named capture.
  • Adds two new regex flags: s, to make dot match all characters (aka dotall or singleline mode), and x, for free-spacing and comments (aka extended mode).
  • Provides a suite of functions and methods that make complex regex processing a breeze.
  • Automagically fixes the most commonly encountered cross-browser inconsistencies in regex behavior and syntax.
  • Lets you easily create and use plugins that add new syntax and flags to XRegExp's regular expression language.
查看更多
登录 后发表回答