Xcode and Regex

The Problem

Have you ever wanted to do a find-and-replace in Xcode like this?

FIND: Created by Alpha on 150301.
REPLACE: Created by Alpha on 150301. Updated by Beta (2017).

The tricky thing here is that the date (150301) probably isn’t going to be consistent throughout your Xcode project, which makes a straightforward find-and-replace impossible. So, if we wanted to include the following cases, we’d be out of luck:

FIND: Created by Alpha on 150112.
REPLACE: Created by Alpha on 150112. Updated by Beta (2017).

FIND: Created by Alpha on 141211.
REPLACE: Created by Alpha on 141211. Updated by Beta (2017).

So, what do we do? Turns out we can take care of all these different cases with regex!

The Solution

OK, let’s start with the actual find and replace values you’ll use, and then we’ll explain them afterwards. Here they are:

FIND: Alpha on (.*)\.
REPLACE: Alpha on $1. Updated by Beta (2017)

That’s the answer… but what does it all mean? If you’re not familiar with regular expressions (e.g., regex), they are basically a very concise way to represent string patterns. They’re not particularly readable, to be honest, but they can be very powerful—especially in Xcode!

There’s a lot of interesting detail to learn, but you won’t need that for now. Here’s all you need to know for this example:

  • You can think of (.*) in the find string as a multiple-character wildcard.
  • If you want to leave the wildcard value unchanged in the new string, just use $1. If we had multiple wildcards in the find string, we’d use $1, $2, and so on in the replace string.
  • You need to “escape” special characters in the find string (e.g., the non-wildcard period) with a backslash. That’s what the extra backslash is for.

The Step-by-step

Got it? OK, so here’s the step-by-step guide to doing a simple regex find-and-replace in Xcode:

  1. Open the Find Navigator (⌘3) and ensure Replace is selected on the top left. (Or just type ⌥⇧⌘F)
  2. Xcode find-and-replace with regular expressions (regex)

  3. Select “Regular Expression” instead of “Text.”
  4. Xcode find-and-replace with regular expressions (regex)

  5. Add your find and replace values from above, press Return to start the search, and that’s it!
  6. Xcode find-and-replace with regular expressions (regex)

Adding a little regex into my Xcode searches has saved me some time, and made big find-and-replace tasks less error-prone too. If you’re looking to learn more about regular expressions, here’s a video tutorial by Lea Verou that I found really helpful. Got any other Xcode find-and-replace tips? Feel free to share them below.

-Alex (@leakywellington)

One thought on “Xcode and Regex

Leave a Reply

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