Regex : Select Everything Between

Let’s say we want to select things between two string patters. For instance the middle of a file path:

/Users/Stuff/Dev/things/stuff/more/things/package.json

We can use something called a look behind and a look ahead to get the match we want. Let’s say in this case I want to pull out: “stuff/more”

First off if you don’t have Reggy, I highly recommend it. You can debug regex quite easily.

Second, what are we talking about with look aheads and look behinds?

Positive Lookbehinds:

For the first bit, we don’t need to start our string pattern at the beginning of the line. We can just start with a positive lookbehind. What is it? It tells the computer to temporarily step backwards in the string to find a matching pattern.

However, all this is bullshit. What you really want to know is this:

(?<=text) = find "text" and match shit to the right

Now we can highlight something like this:

With:
/Users/Stuff/Dev/things/stuff/more/things/package.json

Running (?<=things/):

Outputs: stuff/more/things/package.json

Now we need the second rule.

Positive Lookaheads:

Now we need to remove the stuff on the end “/things/package.json”. To do this, we again need something that sounds really complex and blah blah blah.

What you want to know is this:

(?=text) = find text and match shit to the left

So if you don’t want “/things/package.json” just match everthing to the left of it:

Running: (?=/things/package.json):

Outputs: /Users/Stuff/Dev/things/stuff/more

Putting it all together:

Let’s add everything together and see what we get:

Running: (?<=things/).*?(?=/things/package.json)

Outputs: stuff/more

There you have it!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.