0

Let's say I have a regular expression /([a-z]+):([0-9]+)/ and a sample text hello:123.

Is there a way for me to execute this expression so that it returns all capturing groups along with positions for each group?

For example the result should be something like [["hello", 0], ["123", 6]].

As far as I found, the regular expression only returns the position for the whole match, which is not enough for what I need :( Thanks!

UPDATE:

In PHP, this can be achieved with PREG_OFFSET_CAPTURE flag, but I need the same behaviour for JS

SOLUTION:

In this thread Get index of each capture in a JavaScript regex there is a class MultiRegExp2 which allows for this functionality https://github.com/valorize/MultiRegExp2

Arthur
  • 1,433
  • 1
  • 18
  • 35
  • You could iterate the matches and keep track of the position yourself in the loop... each match may also have the position hidden in a private member or otherwise – Jay Mar 23 '18 at 13:32
  • The thing is, I need all positions within a single match. In PHP there is a `PREG_OFFSET_CAPTURE` flag, but I have no idea how to do the same in JS. – Arthur Mar 23 '18 at 13:45
  • Sounds like a job for split or indexof... and then manually find the offsets at the worst case but using a match collection should also work – Jay Mar 23 '18 at 13:47
  • I am afraid it is more complicated but I've found a solution from this https://stackoverflow.com/questions/15934353/get-index-of-each-capture-in-a-javascript-regex thread. I'll update my question to include the solution – Arthur Mar 23 '18 at 14:07

0 Answers0