Xcode and regex

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

BEFORE: Created by Eddie on 150301.

AFTER: Created by Eddie on 150301. Updated by Patty (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:

BEFORE: Created by Eddie on 150112.

AFTER: Created by Eddie on 150112. Updated by Patty (2017).



BEFORE: Created by Eddie on 141211.

AFTER: Created by Eddie on 141211. Updated by Patty (2017).



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

Find and Replace with Regex

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: Eddie on (.*)\.

REPLACE: Eddie on $1. Updated by Patty (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.

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.

. If we had multiple wildcards in the find string, we’d use , , 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:

Open the Find Navigator ( ⌘3 ) and ensure Replace is selected on the top left. (Or just type ⌥⇧⌘F ) Select Regular Expression instead of Text . Add your find and replace values from above, press Return to start the search, and that’s it!

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? Come share them on Twitter.

— Alex Andrews (@leakywellington)