从字符串中提取货币

时间:2016-04-26 11:44:37

标签: swift2 substring currency

这是Swift 2.1。

你如何从一个看起来像“加蛋(£2.00)”的字符串中提取金额?在这个例子中,我需要“2.00”部分。

难以检查托架之间的任何内容吗?或者有更有效的方法吗?即正则表达式还是什么?

3 个答案:

答案 0 :(得分:1)

'纯'Swift解决方案,无需括号

let str = ["add egg £ 2.00",
           "the price is $12.00 per unit",
           "send €10.22 to somebody",
           "invalid $(12)"]

func value(str: String, currency: String)->Double {
    var chars = str.characters
    let currs = currency.characters

    while !currs.contains(chars.popFirst() ?? " ") {}

    let arr = chars.split(" ")
    guard let value = arr.first,
        let d  = Double(String(value)) else { return Double.NaN }
    return d
}

let values = str.flatMap { value($0, currency: "£$€") }
print(values)
/*
 [2.0, 12.0, 10.220000000000001, nan]
 */

如果你真的需要括号,没问题......

let str = ["add egg (£2.00)",
           "the price is ($12.00) per unit",
           "send (€10.22) to somebody",
           "invalid ($-12)"]

func value(str: String, currency: String)->Double {
    var chars = str.characters
    let currs = currency.characters

    while !currs.contains(chars.popFirst() ?? " ") {}

    let arr = chars.split(")")
    guard let value = arr.first,
        let d  = Double(String(value)) else { return Double.NaN }
    return d
}

let values = str.flatMap { value($0, currency: "£$€") }
print(values)
/*
 [2.0, 12.0, 10.220000000000001, -12.0]
 */

答案 1 :(得分:0)

有很多方法可以实现你想要的东西 - 这是一个带正则表达式的简单例子。

我正在使用(?<=\\()[^\\)]+查找()之间的任何内容,然后我使用几个范围来提取值:一个用于货币符号,另一个用于值

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

在String上调用方法,然后安全地打开可选结果:

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)'")
}

打印:

  

货币为'£',价值为'2.00'

答案 2 :(得分:-1)

var myString = "add egg (£2.00)"
myString = myString.stringByReplacingOccurrencesOfString("", withString: "")
let components = myString.componentsSeparatedByString("add egg (£")
let finalString = components[1].stringByReplacingOccurrencesOfString(")", withString: "")
print(finalString)

//打印2.00