Hello, my name is: Amy

Regular Expressions

There's been a few times where I have needed to solve a problem in Sublime Text by selecting specific bits of information (such as a new line).

Regular Expression search is allowed in Sublime Text by clicking on the asterick.

Regex search button in Sublime Text

This particular problem was that I had a bunch of files where I needed to update certain hard coded links from http:// to https://. However, there were other links that needed to be left alone (ones in comments, or ones used for HTML doctype).

In order to get the best use out of the regex, I first tried to figure out some rules for what I would be looking for:

Here's some examples of situations I had:

<html doctype="http://w3.org">
//This is from the jquery library found at http://jquery.org

    <a href="http://something.google.com">Link</a>
    <a href='http://something.client.com'>Link</a>
    <a href="http://somethingelse.client.com">Link</a>

</html>
  • In order to now worry about the comments, I needed to only select links that were preceded directly by a ' or '.

  • I needed to not worry about links that were not associated with google or with client.com, so links that would be http:// + something + google.com OR http:// + something + client.com

Building that expression:

The thing about regular expressions is that they look crazy at first glance. Turns out parenthesis are the secret key to figure out what the heck is going on.

((?<=('|"))http:\/\/(?=\w+\.(client|google)))

Let's strip it down by first removing the containing parenthesis on the ends.

(?<=('|"))   http:\/\/   (?=\w+\.(client|google))

Starting to get some semblance of order, now you can see there are three distinct parts.

  1. What we are searching for. (The coral part.)
  2. What should be before that. (The first pink area.) (?<= )
  3. What should be after our search phrase. (The second green bit.) (?= )

Comments