How to use regular expressions in Swift 3?

I wanted to follow this tutorial to learn about NSRegularExpression in Swift , but it has not been updated to Swift 3 . When I open a playground with examples they provide, I get a few errors, which are one of them:

 let regex = NSRegularExpression(pattern: pattern, options: .allZeros, error: nil) 

I saw that the initializer now throws an exception, so I changed the call, but this .allZeros no longer exists. I do not find a tutorial or an example with an equivalent in Swift 3 , can someone tell me which option should now replace such an .allZeros option?

+6
source share
2 answers

I believe .allZeros should have been used when no other parameters were applied.

So, with Swift 3, you can either pass an empty list of parameters or leave the options parameter, because by default it has no parameters:

 do { let regex = try NSRegularExpression(pattern: pattern, options: []) } catch { } 

or

 do { let regex = try NSRegularExpression(pattern: pattern) } catch { } 

Note that in Swift 3 you no longer use the error parameter. Now he is throws .

+7
source

You can use [] :

 let regex = try! NSRegularExpression(pattern: pattern, options: []) 

which is also the default, so you can omit this argument:

 let regex = try! NSRegularExpression(pattern: pattern) 

The easiest way to find this is to press + go to the definition of the methods:

 public init(pattern: String, options: NSRegularExpression.Options = []) throws 
+5
source

Source: https://habr.com/ru/post/1013041/


All Articles