Search code examples
phpregexlookbehind

How can I implement variable width look behind regex to get a list of items?


I have a list of items which is prefixed by its type in this case 'fruits' , now I need the list of all fruits and its counts

fruits 5 apples, 2 oranges, 3 bananas

the regular expression which I am tried

(?<=fruits\s)((?<count>\d{1,})\s(?<fruit>\w{1,},))

but this gets me the first fruit and its count, but I want list of all fruits with their count, so I tried this

(?<=fruits\s((?:\d{1,})\s(?:\w{1,},))*)((?<count>\d{1,})\s(?<fruit>\w{1,},))

but I get the error saying that look behinds should be fixed width!

I have tried a sample here: http://regex101.com/r/oE6jJ1/1


Solution

  • Use the below regex and get the count from group index 1 and fruit name from group index 2.

    (?:^fruits|(?<!^)\G)\h*\K(?<count>\d*)\h*(?<fruit>\w*)
    

    DEMO