I have a string like this:
Hello [@foo] how are you [@bar] more text
Ultimately I need to modify each instance of a substring matching /\[@.+?\]/
, but I also need to modify each substring before/after the [@foo]
and [@bar]
.
The following regex matches the substring before a [@.+]
, the [@.+]
itself, then a substring after the [@.+]
until the next character is followed by another [@.+]
.
(.*?)(\[(@.+?)\])((.(?!(\[@.+?\])))*)
So the first match is "Hello [@foo] how are you" and the second match is " [@bar] more text".
Note the space at the beginning of the second match. That's the problem. Is there a way to get the first match to include all characters right up to the next [@.+]
?
My regex includes characters after the [@.+]
that are not followed by an instance of [@.+]
, and I cannot see any way of getting it to include all characters until we are actually in another instance of [@.+]
.
I'm really interested in whether I'm missing something - it certainly feels like there should be a simpler way to capture the characters around a given match, or a simpler way to capture characters not part of a match...