从swift中的字符串中提取值

问题描述 投票:0回答:2

我有一个字符串"25% off",我想从中提取唯一的值25,我怎么能在swift中提取它,之前我已经完成了目标c但是在快速锄头中我们能做到吗?我试过这段代码却失败了,

 let discount = UserDefaults.standard.string(forKey: "discount")
    print(discount)
    let index = discount?.index((discount?.startIndex)!, offsetBy: 5)
    discount?.substring(to: index!)
    print(index)

我怎么能从中得到25?

ios swift4
2个回答
1
投票

一个聪明的解决方案是使用正则表达式从字符串的开头找到所有连续数字的范围,index方式不是很可靠。

let discount = "25% off"
if let range = discount.range(of: "^\\d+", options: .regularExpression) {
    let discountValue = discount[range]
    print(discountValue)
}

您甚至可以使用模式"^\\d+%"搜索包含百分号的值


0
投票

您可以使用数字字符集从该字符串中提取数字:

let discount = "25% off"
let number = discount.components(separatedBy: 
             CharacterSet.decimalDigits.inverted).joined(separator: "") 
print(number) // 25

请务必使用倒置变量,否则您将获得非数字。

© www.soinside.com 2019 - 2024. All rights reserved.