Reputation: 155
I am new in swift, I have been working with it only few weeks and now I am trying to parse something like a price list from incoming string. It has the next format: 2.99 X 3.00 = 10 A Some text here 1.22 X 1.5 10 A
And the hardest part is that sometime A or some digit is missing but X should be in the place. I would like to find out how it is possible to use regex in swift (or something like that if it does not exist) to write a template for parsing the next value d.dd X d.d SomeValueIfExists
I would very appreciate any useful information, topics to read or any other resources to get more knowledge about swift.
PS. I have access to the dev. forums but I've never used them before.
Upvotes: 2
Views: 737
Reputation: 19524
I did an example recentl, and maybe a little harder than necessary, to demonstrate RegEx use in Swift:
let str1: NSString = "I run 12 miles"
let str2 = "I run 12 miles"
let match = str1.rangeOfString("\\d+", options: .RegularExpressionSearch)
let finalStr = str1.substringWithRange(match).toInt()
let n: Double = 2.2*Double(finalStr!)
let newStr = str2.stringByReplacingOccurrencesOfString("\\d+", withString: "\(n)", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
println(newStr) //I run 26.4 miles
Two of these have "RegularExpressionSearch". If you put this in a playground you can see what each line does. Note the double \ escapes. One for the normal RegEx use and anther because \ is a special character in Swift.
Also a good article:
http://benscheirman.com/2014/06/regex-in-swift/
Upvotes: 1