NSRegularExpression initializer fails to compile in Swift 4.2

In swift 4.2 I am trying to write the following code:

let regex = NSRegularExpression(
pattern: "\w[A-Z]",
options: NSRegularExpression.Options.allowCommentsAndWhitespace
)

This initializer shows up in the autocomplete, but when I try to build, I get the following 2 errors:


- Incorrect argument label in call (have 'options:', expected 'coder:')

- Invalid escape sequence in literal


It seems like a bug, but I could also be doing something wrong!

Answered by samjohn in 337096022

Solved!

1. The problem was in the xcode autocomplete, for swift 4.2 the API is actually

NSRegularExpression(pattern: "")


2. The invalid escape sequence was due to needing to escape the backslash.


So the following works:


let regex = try NSRegularExpression(pattern: "\\w[A-Z]")
Accepted Answer

Solved!

1. The problem was in the xcode autocomplete, for swift 4.2 the API is actually

NSRegularExpression(pattern: "")


2. The invalid escape sequence was due to needing to escape the backslash.


So the following works:


let regex = try NSRegularExpression(pattern: "\\w[A-Z]")

It's because you are not writing a String literal correctly.

When you want to pass \w to NSRegurlarExpression, the character \ needs to be escaped.


do {
    let regex = try NSRegularExpression(
        pattern: "\\w[A-Z]",
        options: NSRegularExpression.Options.allowCommentsAndWhitespace
    )
    //Use `regex` ...
} catch {
    print(error)
}


Seems you found it yourself. By the way, both `NSRegularExpression.init(pattern:)` and `NSRegularExpression.init(pattern:options:)` are valid.

It's because you are not writing a String literal correctly.

FYI, a future Swift will make this easier by way of SE-0200 Enhancing String Literals Delimiters to Support Raw Text. Alas, this is not in Swift 4.2.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
NSRegularExpression initializer fails to compile in Swift 4.2
 
 
Q