Search code examples
regextextmateoniguruma

Regex problems in TextMate


Regular Expressions are new to me (yet they are wonderful and useful :D). However, after trying to use them in TextMate, I'm getting unexpected results. I'm not sure if that's a bug or that's how regular expressions work.

I have this code

begin text in the middle end and more text and a
second begin second text in the middle end

Searching with begin.+end I would expect two results

  1. begin text in the middle end and
  2. begin second text in the middle end

But I get the whole text selected; I would expect begin.+end to search for .+ until the first end is found, but it searches until the last one.

Is that how they work? Where could I learn how to use regular expressions?

The truth is I'm interested in just selecting the inside .+ without begin and end but that's another question.


Solution

  • Use the below regex to get the strings between begin and end,

    (?<=begin).+?(?=end)
    

    DEMO

    Explanation:

    • (?<=begin) Positive look-behind is used to match after a specific pattern. In this, regex engine sets the matching marker just after to begin.
    • .+? Matches one or more characters.? makes the regex non-greedy so it would results in a shortest match.
    • (?=end) Once it finds the string end, regex engine stops matching. Thus giving you the characters between begin and end.