match-index
Get index of each capture.
- Get index of each capture in a JavaScript regex - Stack Overflow
- tc39/String.prototype.matchAll: ES Proposal, specs, tests, reference implementation, and polyfill/shim for String.prototype.matchAll
Why?
You want to match a regex like /(a.)(b)(c.)d/
with "aabccde", and get the following information back:
"aa" at index = 0
"b" at index = 2
"cc" at index = 3
But, it is difficult to write.
match-index
provide matchCaptureGroupAll
function that easy to get this information!
const text = "aabccde";const regExp = /d/;const captureGroups = ;// array of `MatchCaptureGroup`assert;const a b c= captureGroups;assert;assert;assert;assert;assert;assert;
Installation
npm install match-index
Usage
match-index
provide two functions
matchCaptureGroupAll(text, regExp): MatchCaptureGroup
Retrieves the captured matches when matching a string against a regular expression.
Example of matchCaptureGroupAll()
// get "ABC" and "EFC that are captured by ( and )const captureGroups = ;// captureGroups is array of MatchAllGroup/** * @typedef * @property * @property * @property * @property */;const x y = captureGroups;assert;assert;assert;assert;
matchCaptureGroupAll
use matchAll
in internal.
matchAll(text, regExp): MatchAllGroup
Retrieves the matches all when matching a string against a regular expression.
Example of matchAll()
const text = 'test1test2';const regexp = /t/g;const captureGroups = ;// captureGroups is array of `MatchAllGroup`/** * @typedef * @property * @property * @property * @property */ assert;const test1 test2 = captureGroups;assert;assert;assert;assert;assert;assert;assert;assert;
Notes
Limitation ⚠️
matchAll
and matchCaptureGroupAll
doesn't support nest capture.
e.g.) last captureGroups item's index
is wrong result.
(st(\d?))
is nest capture.
const text = 'test1test2';const regexp = /t/g;const captureGroups = ;// captureGroups is array of `MatchAllGroup`/** * @typedef * @property * @property * @property * @property */ assert;const test1 test2 = captureGroups;assert;assert;assert;assert;
Welcome to pull request to fix this limitation :)
Tests
npm test
Contributing
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request :D
License
MIT