Search code examples
regexsublimetext3

Sublime Text - REGEX: How to match a word in a string?


I'm using "find in Files" function of Sublime to search for a specific word in a specific string, that repeats on multiples files.

Something like that:

tags: TAG1 TAG2 TAG3 TAG4
alias: ALIAS1, ALIAS2`

I was Trying to find "TAG2", between "tags" and "alias", and was thinking on a REGEX Expression like this:

(?s)(?<=tags)TAG2(?=alias)

Inspired on this Previous Question, but the REGEX syntax for Sublime is different and I've been unable to adapt it.

Any ideas? Thx.


Solution

  • For the example data with 2 lines:

    ^tags:.*\K\bTAG2\b(?=.*\Ralias:)
    

    The pattern matches:

    • ^ Start of string
    • tags: Match literally
    • .* Match the rest of the line
    • \K Forget what is matched so far (so do not include in the match)
    • \bTAG2\b Match the "word" TAG2 between word boundaries
    • (?= Positive lookahead, assert what to the right is
      • .*\R Match the rest or the line and a newline
      • alias: Match literally
    • ) Close the lookahead

    See a regex demo

    Note that if you use (?s) the . will match any character including a newline, so .* can span multiple lines.