Whimusical
Whimusical

Reputation: 6629

Repeated capturing groups in regex when only last match is allowed (workaround)

I got an string like

*hello world,hello2 world2,hello3 world3,..., helloN worldN *

I want to match repitedly hello worlds and capture only hello words in a global (/g) level for a multiline string, where that pattern is founf occasionally

If I define a repeated group with hello captured *(?:(\w+)\s\w+,?)+* only the last helloN is matched due to http://www.regular-expressions.info/captureall.html

If I define a capturing group looking for the repeated hellos *((\w+)+)* Then my problem is that the match is not done, as it is checking against *hello world,hello2 world2,hello3 world3* or everything within two asterisks with that pattern

The result should be

- hello hello2 hello3 ... hello n

I think the key is finding a way to force to match the repeating group whereas the captured group is returning multiple outputs

Upvotes: 1

Views: 755

Answers (1)

Farvardin
Farvardin

Reputation: 5424

use this:

(?<=[,*])(\w+)(?=\s\w+[,*])

see DEMO

Upvotes: 1

Related Questions