rocket101
rocket101

Reputation: 7537

RegEx in Swift?

I am learning Swift, and I have (another) question. Are there regular espressions in Swift, and, if so, how do I use them?

In my research, I found some conflicting information. Apple Developer documents has something mentioning RegEx, but it looks so different than any other language i've seen. If this is the solution, how do I use it?

This website, on the other hand, suggests that RegEx doesn't exist in Swift. Is this correct?

In case it helps, I am trying to use regex to get the average price of a bitcoin from JSON-style API that contains the price, but also a lot of stuff I don't want.

Sorry for another basic question.

Upvotes: 13

Views: 14335

Answers (4)

Shai Mishali
Shai Mishali

Reputation: 9382

Another easy option is to use NSPredicate if what you're interesting in is pure validation (true/false):

Here's a quick Regex to match a Canadian Postal code:

func isCAZipValid(_ zip: String) -> Bool {
    return NSPredicate(format: "SELF MATCHES %@", "^([A-Z]\\d[A-Z])(\\s|-)?(\\d[A-Z]\\d)$")
             .evaluate(with: zip.uppercased())                
}

Upvotes: 1

ningsuhen
ningsuhen

Reputation: 241

I faced the same problem. So, I wrote a small wrapper - https://gist.github.com/ningsuhen/dc6e589be7f5a41e7794. Add the Regex.swift file in your project and add "Foundation" framework if not already added. Once you do that, you can use the replace and match methods as follows.

"+91-999-929-5395".replace("[-\\s\\(\\)]", template: "") //replace with empty or remove
"+91-999-929-5395".match("[-\\s\\(\\)]") //simple match - returns only true or false, not the matched patterns.

Upvotes: 4

Encore PTL
Encore PTL

Reputation: 8214

Swift doesn't have regex so you will need to implement a wrapper class yourself or use some library like this which implements Regex class http://www.dollarswift.org/#regex

Upvotes: -2

Michael Ho Chum
Michael Ho Chum

Reputation: 939

Unfortunately, Swift is lacking regex literals. But the external link you are referring to exposes 2 ways to use regex.

  1. Make a class wrapper around NSRegularExpression and use this class.
  2. Calling the Foundation method rangeOfString:options: with RegularExpressionSearch as option. This in Swift.

The 2nd way is cleaner and simpler to implement.

The method method definition in Swift

func rangeOfString(_ aString: String!,options mask: NSStringCompareOptions) -> NSRange

You can use it with regex matching as:

let myStringToBeMatched = "ThisIsMyString"
let myRegex = "ing$"
if let match = myStringToBeMatched.rangeOfString(myRegex, options: .RegularExpressionSearch){
    println("\(myStringToBeMatched) is matching!")
}

Here's Apple's documentation on rangeOfString()

Upvotes: 31

Related Questions