Search code examples
regexcapturing-group

Regex - capture all repeated iteration


I have a variable like this

var = "!123abcabc123!"

i'm trying to capture all the '123' and 'abc' in this var.

this regex (abc|123) retrieve what i want but...

My question is: when i try this regex !(abc|123)*! it retrieve only the last iteration. what will i do to get this output

MATCH 1
1.  [1-4]   `123`
MATCH 2
1.  [4-7]   `abc`
MATCH 3
1.  [7-10]  `abc`
MATCH 4
1.  [10-13] `123`

https://regex101.com/r/mD4vM8/3

Thank you!!


Solution

  • If your language supports \G then you may free to use this.

    (?:!|\G(?!^))\K(abc|123)(?=(?:abc|123)*!)
    

    DEMO