Search code examples
regexnsregularexpression

Can't create NSRegularExpression because of "Couldn't create (Metatype) escape NSRegularExpression"


I'm trying to create the following NSRegularExpression (I'm trying to find all commas ,, left-parens (, right-parens ), and backslashes \):

var error: NSError?
NSRegularExpression(pattern: "[,\\(\\)\\]", options: nil, error: &error)

But it returns .None with the following error:

Couldn't create (Metatype) escape NSRegularExpression

And the following userInfo:

NSInvalidValue: "[,\(\)\]"

What does this mean?


Solution

  • My backslash literal inside the character class wasn't properly escaped. It used two backslashes inside the string literal instead of four.

    var error: NSError?
    NSRegularExpression(pattern: "[,\\(\\)\\]", options: nil, error: &error)
    

    Should be:

    var error: NSError?
    NSRegularExpression(pattern: "[,\\(\\)\\\\]", options: nil, error: &error)
    

    I think the Couldn't create (Metatype) escape error refers to the incompletely escaped backslash leading to escaping the final square bracket, which makes the character class definition invalid.