Search code examples
swift2substringcurrency

Extracting currency from string


This is Swift 2.1.

How would you go about extracting an amount from a string that looks like "add egg (£2.00)"? In this example, I would need the "2.00" portion.

Would it be a hard-check looking for whatever's enclosed between the brackets? Or is there a more effective way to do so? I.e. regex or something?


Solution

  • There's many ways to achieve what you want - here's a simple example with a regex.

    I'm using (?<=\\()[^\\)]+ to find anything between ( and ), then I use a couple of ranges to extract the values: one for the currency symbol, another for the value.

    extension String {
        func extractValueBetweenParenthesis() -> (currency: String?, value: String?) {
            if let range = self.rangeOfString("(?<=\\()[^\\)]+", options: .RegularExpressionSearch) {
                let cr = range.startIndex..<range.startIndex.advancedBy(1)
                let vr = range.startIndex.advancedBy(1)..<range.endIndex
                return (currency: self.substringWithRange(cr), value: self.substringWithRange(vr))
            }
            return (nil, nil)
        }
    }
    

    Call the method on a String then safely unwrap the optional results:

    let str = "add egg (£2.00)"
    let result = str.extractValueBetweenParenthesis()
    if let currency = result.currency, value = result.value {
        print("Currency is '\(currency)' and value is '\(value)'")
    }
    

    Prints:

    Currency is '£' and value is '2.00'