slevithan / xregexp

Extended JavaScript regular expressions
http://xregexp.com/
MIT License
3.31k stars 278 forks source link

How to access just the named groups? #298

Closed slhck closed 4 years ago

slhck commented 4 years ago

I'm a little confused with named groups capturing.

Given:

const text = 'Foo Bar';
const regex = XRegExp('\\w+(?<test> Bar)');
const result = XRegExp.exec(text, regex);
console.log(result);

I get:

[
  'Foo Bar',
  ' Bar',
  index: 0,
  input: 'Foo Bar',
  groups: undefined,
  test: ' Bar'
]

I don't understand why groups is undefined and what I would have to do to make it populated with test: ' Bar'.

I see that #175 added support for something like this, but I'm not sure why this is not documented or how it can be used.

slhck commented 4 years ago

I see that using the namespacing feature, the test passes:

XRegExp.install('namespacing');
const text = 'Foo Bar';
const regex = XRegExp('\\w+(?<test> Bar)');
const result = XRegExp.exec(text, regex);
expect(result?.groups?.test).toEqual(' Bar');

Could this be added to the website or usage examples? I don't see it documented anywhere, and it would saved me a few hours of scratching my brain yesterday :)

C0ZEN commented 4 years ago

@slhck I just had the exact same problem.

By checking the types though it is documented as JSDoc.

/**
 * Represents an array of matched values.
 */
interface ExecArray extends RegExpExecArray, Array<string> {
  /**
   * Named capture groups are accessible as properties when the `namespacing`
   * feature is not installed.
   */
  [propName: string]: any;

  /**
   * This is only present if the the `namespacing` feature is installed
   * using the `XRegExp.install` method.
   */
  groups?: NamedGroupsArray;
}

But I wanted to see what is the best practice to use XRegExp.install and I did not saw an usage on the pages on the left from the website and also there is no search bar 😞

slevithan commented 4 years ago

Yes, the documentation on xregexp.com needs to be updated to the latest XRegExp version, and ideally the source of the documentation added to the project here so others can help keep it up to date.