Tometoyou Tometoyou - 5 days ago 6
Swift Question

Regex pattern to find force unwrapped variables

I want to find all the force unwrapped variables in my Xcode project. For example anything that's similar to:

variableName!.property


or

variableName!,


or

variableName! : otherVariable


or

variableName!)


Or any other similar occurrences of force unwrapped variables. What would be a regex pattern for that that I can use in the Xcode search?

Answer

This one will search for only valid variable names (alphanumeric strings starting with a letter) that are followed by an ! which is then followed by a space, tab, newline, or a period, comma, or colon. This search also excludes finding instances of try! and as!.

([A-z]+[A-Za-z0-9]*(?<![(try)(as)])![.,:\n\t\r ])

This next pattern will match try! and as! if you are interested in finding those as well.

([A-z]+[A-Za-z0-9]*![.,:\n\t\r ])

It should be noted both of these patterns will also match for variable types that are force unwrapped optionals (a common variable to be force unwrapped being @IBOutlets)

A really good resource for writing and testing regular expressions is regexr.com