這是Swift 2.1。從字符串中提取貨幣
你將如何去提取一個字符串,看起來像「添加蛋(£2.00)」的金額?在這個例子中,我需要「2.00」部分。
難道要檢查括號內的任何內容嗎?還是有更有效的方法呢?即正則表達式或什麼?
這是Swift 2.1。從字符串中提取貨幣
你將如何去提取一個字符串,看起來像「添加蛋(£2.00)」的金額?在這個例子中,我需要「2.00」部分。
難道要檢查括號內的任何內容嗎?還是有更有效的方法呢?即正則表達式或什麼?
有很多方法可以實現你想要的東西 - 這裏有一個簡單的例子,用正則表達式。
我使用(?<=\\()[^\\)]+
找到(
和)
之間的任何東西,然後我用了幾個範圍,以提取值:一個是貨幣符號,另一個用於值。
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)
}
}
呼叫上的字符串的方法然後安全地解開該可選的結果:
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'
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
爲什麼投了票,它在工作,當你測試它時有什麼問題? –
那不是我:)今晚會試一試。 – Polis
'純'快速解決方案,無需支架
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]
*/
謝謝你,這是偉大的,但我接受了reggex的答案,因爲它更接近我的要求 – Polis
你的字符串「加雞蛋(£2.00)」應該總是在這種模式? 我的意思是,「添加(£)」 –
NSAnant
現在,是的。但是,如果模式需要在未來發生變化,我想讓事情更具活力,從而按照正則表達式思考。 – Polis
爲正則表達式,你需要一個修補程序來匹配。 – NSAnant