regexregex-groupregex-greedy

words selection


"highlight" the searched desired word. What i'm trying to achieve: clicking on the next or previous button i want to select only the underlined single word and navigate in sequence back and forth on the words founded. So, how can i do, having five words founded,to select only the third word after the first two? ex. :

enter image description here

i've tried this expression : ^(?:\w+ ){2}\K\w+ but making some test i cannot able to find my desired result.


Solution

  • The following regex matches only the 3rd hello: demo

    (?<=(?:Hello.*){2})(?<!(?:Hello.*){3})Hello
    

    This is using a positive lookbehind to test if at least 2 "Hello"s have been passed, and a negative lookbehind to test if 3 or more have not been passed. If at least 2 have been passed and not 3 or more then only 2 "Hello"s have passed.