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.
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.
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.
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.
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.
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())
}
Unfortunately, Swift is lacking regex literals. But the external link you are referring to exposes 2 ways to use regex.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With