Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 506
rocket101 Avatar asked Aug 01 '14 01:08

rocket101


People also ask

What is regex Swift?

Regex is a struct generic over its Output, which is the result of applying it, including captures. You can create one using a literal containing regex syntax in between slash delimiters. Swift's regex syntax is compatible with Perl, Python, Ruby, Java, NSRegularExpression, and many, many others.

What is regex in iOS?

A regex ( also known as regular expressions) is a pattern string. These pattern strings allow you to search specific patterns in documents and to validate email, phone number etc. In iOS and MacOS regex been handled by NSRegularExpression . To know more about NSRegularExpression read apple documentation.

What is regex used for?

A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.

Is regex good for parsing?

Regex isn't suited to parse HTML because HTML isn't a regular language. Regex probably won't be the tool to reach for when parsing source code. There are better tools to create tokenized outputs. I would avoid parsing a URL's path and query parameters with regex.


2 Answers

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())                
}
like image 60
Shai Mishali Avatar answered Oct 03 '22 04:10

Shai Mishali


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()

like image 44
Michael Ho Chum Avatar answered Oct 03 '22 02:10

Michael Ho Chum