I had to convert a long list of error codes from C# to a Swift enum, and thought this would be a great opportunity to use regular expressions.

Error codes looked like this example:

ConsumerSchedulingInfoNotFound = 304,

I’m using an enum with String rawValue, so it can be easily initialized from JSON. The same error code in the enum would look like this:

case consumerSchedulingInfoNotFound = "ConsumerSchedulingInfoNotFound"

Doing this conversion manually over a list of over a hundred error codes would be tedious. Regular expressions to the rescue!

Using Regular Expressions to search text in Xcode

In the search panel, click on the “Text” label and a dropdown will appear:

Screen Shot 2021-01-07 at 11 44 49 AM

Select “Regular Expression”: Screen Shot 2021-01-07 at 11 45 01 AM

In my case, I used the following expression:

(\w+) = \d+,

The first part on the left, \w+, fill match any “word” characters. The ‘+’ indicates there must be one letter, or more. It is wrapped into parenthesis to indicate we want to capture the value. In regular expressions, parenthesis are capture groups.

The rest of the expression matches the equal symbol, with spaces, and an integer number (again, one or more digits) followed by a comma. All the text in the expression will be replaced.

To enter search/replace form, tap on “Find” and a dropdown will appear. Select “Replace”:

Screen Shot 2021-01-07 at 11 50 26 AM

Replacing text in Xcode using captured values from regular expressions

In the replacement text box we can now use the captured groups from the search expression. In my case, the replacement looks as follows:

case $1 = "$1"

$1 denotes the first capture group. Note $0 is available too, but that contains the entire matched text. If we had multiple capture groups (multiple sets of parenthesis), we would use $2, $3, etc.

The enum case name will have the error code, and the raw value string will use the same value, between double quotes.

Uppercase & lowercase with regular expressions in Xcode

Unfortunately, Xcode does not seem to support Boost escape codes for regular expressions, so I might have to manually lowercase the first letter of the error code. Swift does not require doing this, but I prefer this syntax.

This article was written as an issue on my Blog repository on GitHub (see Issue #22)

First draft: 2021-01-07

Published on: 2021-01-07

Last update: 2021-01-07