Home > Back-end >  Return everything starting from last occurrence of pattern
Return everything starting from last occurrence of pattern

Time:09-12

Consider this string:

apple banana carrot dessert carrot carrot apple banana banana carrot dessert dessert

I want to match and return everything starting from the last occurrence of "carrot" (whether it's itself included or not — let's say it should be), which would give:

carrot dessert dessert

This is the farthest I've gotten:

. (carrot. )$

Demo regex101

I'm not sure how to return only Group 1 and not the entire Group 0 (which Group 1 is a part of). Clearly I'm misunderstanding some basic mechanics of regex. Thank you for reading.

I'm coding an AutoHotKey script.

CodePudding user response:

str := "apple banana carrot dessert carrot carrot apple banana banana carrot dessert dessert"
RegExMatch(str, "O).*(carrot.*)", o)
MsgBox % o[1]

CodePudding user response:

AutoHotKey supports PCRE so you can indeed make use of \K as pointed out by anubhava in the comments.

If you also want to match carrot if it is the only thing in the line, you can write the pattern using .* which means 0 or more, instead of . which means 1 or more.

.*\K\bcarrot\b.*

Regex demo

  • Related