slevithan/xregexp

Wrong example code

h-h-h-h opened this issue · 2 comments

Link: https://xregexp.com/api/#exec

Wrong code:

// Basic use, with named backreference
let match = XRegExp.exec('U+2620', XRegExp('U\\+(?[0-9A-F]{4})'));
match.groups.hex; // -> '2620'

// With pos and sticky, in a loop
let pos = 2, result = [], match;
while (match = XRegExp.exec('<1><2><3><4>5<6>', /<(\d)>/, pos, 'sticky')) {
  result.push(match[1]);
  pos = match.index + match[0].length;
}
// result -> ['2', '3', '4']

Correct code (changed lines bold and italic):

// Basic use, with named backreference
let match = XRegExp.exec('U+2620', XRegExp('U\\+(?<hex>[0-9A-F]{4})'));
match.groups.hex; // -> '2620'

// With pos and sticky, in a loop
let pos = 3, result = [], match;
while (match = XRegExp.exec('<1><2><3><4>5<6>', /<(\d)>/, pos, 'sticky')) {
  result.push(match[1]);
  pos = match.index + match[0].length;
}
// result -> ['2', '3', '4']

When searching for it in the repo, there were multiple similar occurrences. So, I don't know where to change it.

But in the search results I already saw (?<hex>. I just had the same problem while writing this markdown, the problem that <hex> was hidden when I wrote:

<pre>
// Basic use, with named backreference
<b><i>let match = XRegExp.exec('U+2620', XRegExp('U\\+(?<hex>[0-9A-F]{4})'));</i></b>

I solved it by using &lt;. So, for you, it may also have to do with <hex> being interpreted as an HTML tag.

And don't forget the incorrect starting position.

Oof. Thanks for catching and reporting that. I'll fix the example code/docs in all relevant locations.

xregexp.com has been updated with the documentation fix.

The updates to the example code/docs also just went out with some other small improvements in XRegExp v5.1.1.