如何使用Swift 3修剪String

时间:2017-06-15 13:34:22

标签: ios swift3 character-trimming

我的代码段是:

unwanted = " £€₹jetztabfromnow"

let favouritesPriceLabel = priceDropsCollectionView.cells.element(boundBy: UInt(index)).staticTexts[IPCUIAHighlightsPriceDropsCollectionViewCellPriceLabel].label
let favouritesPriceLabelTrimmed = favouritesPriceLabel.components(separatedBy: "jetzt").flatMap { String($0.trimmingCharacters(in: .whitespaces)) }.last

favouritesHighlightsDictionary[favouritesTitleLabel] = favouritesPriceLabelTrimmed

我的问题是,这不起作用:

let favouritesPriceLabelTrimmed = favouritesPriceLabel.components(separatedBy: unwanted).flatMap { String($0.trimmingCharacters(in: .whitespaces)) }.last

我的价格“从3,95€” - 我想减少所有货币“£”和“来自”或“ab”等字样

你有解决方案,我可以在这里使用吗?

5 个答案:

答案 0 :(得分:1)

我不会试图替换或删除正确的字符或使用正则表达式,而是使用Foundation的内置语言标记支持。它将对字符串进行词法分析并返回各种类型的令牌。在这种字符串上使用它,它应该可靠地找到字符串中的任何数字。

类似的东西:

var str = "from 3,95 €"

let range = Range(uncheckedBounds: (lower: str.startIndex, upper: str.endIndex))

var tokenRanges = [Range<String.Index>]()

let scheme = NSLinguisticTagSchemeLexicalClass
let option = NSLinguisticTagger.Options()
let tags = str.linguisticTags(in: range, scheme: scheme, options: option, orthography: nil, tokenRanges: &tokenRanges)
let tokens = tokenRanges.map { str.substring(with:$0) }

if let numberTagIndex = tags.index(where: { $0 == "Number" }) {
    let number = tokens[numberTagIndex]
    print("Found number: \(number)")
}

在此示例中,代码打印“3,95”。如果您将str更改为“从£28.50”,则会打印“28.50”。

答案 1 :(得分:0)

您可以删除alphanumerics

按特殊字符进行过滤
extension String {

    func removeCharacters(from forbiddenChars: CharacterSet) -> String {
        let passed = self.unicodeScalars.filter { !forbiddenChars.contains($0) }
        return String(String.UnicodeScalarView(passed))
    }
}

let str = "£€₹jetztabfromnow12"

let t1 = str.removeCharacters(from: CharacterSet.alphanumerics)
print(t1) // will print: £€₹

let t2 = str.removeCharacters(from: CharacterSet.decimalDigits.inverted)
print(t2) // will print: 12

更新1:

var str = "£3,95SS"

str = str.replacingOccurrences(of: ",", with: "")

let digit = str.removeCharacters(from: CharacterSet.decimalDigits.inverted)
print(digit) // will print: 395

let currency = str.removeCharacters(from: CharacterSet.alphanumerics)
print(currency) // will print: £

let amount = currency + digit
print(amount) // will print: £3,95

更新2:

let string = "£3,95SS"

let pattern = "-?\\d+(,\\d+)*?\\.?\\d+?"
do {
    let regex = try NSRegularExpression(pattern: pattern, options: [])
    if let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.utf16.count)) {
        let range = match.range
        let start = string.index(string.startIndex, offsetBy: range.location)
        let end = string.index(start, offsetBy: range.length)
        let digit = string.substring(with: start..<end)
        print(digit) //3,95

        let symbol = string.removeCharacters(from: CharacterSet.symbols.inverted)
        print(symbol) // £

        print(symbol + digit) //£3,95

    } else {
        print("Not found")
    }
} catch {
    print("Regex Error:", error)
}

答案 2 :(得分:0)

一种方法是将不需要的字符串放入数组中,并使用String的replacingOccurrences(of:with:)方法。

let stringToScan = "£28.50"
let toBeRemoved = ["£", "€", "₹", "ab", "from"]
var result = stringToScan
toBeRemoved.forEach { result = result.replacingOccurrences(of: $0, with: "") }
print(result)

......收益率&#34; 28.50&#34;。

答案 3 :(得分:0)

如果您只想使用正则表达式提取数值,则会考虑逗号或点小数分隔符。

let string = "from 3,95 €"

let pattern = "\\d+[.,]\\d+"
do {
    let regex = try NSRegularExpression(pattern: pattern, options: [])
    if let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.utf16.count)) {
        let range = match.range
        let start = string.index(string.startIndex, offsetBy: range.location)
        let end = string.index(start, offsetBy: range.length)
        print(string.substring(with: start..<end)) // 3,95
    } else {
        print("Not found")
    }
} catch {
    print("Regex Error:", error)
}

答案 4 :(得分:0)

我问你是否有这个字符串的固定语言环境,因为那时你可以使用语言环境来确定小数分隔符是什么:例如,在故事板中试试这个。

let string = "some initial text 3,95 €" // define the string to scan

// Add a convenience extension to Scanner so you don't have to deal with pointers directly.
extension Scanner {
    func scanDouble() -> Double? {
        var value = Double(0)
        guard scanDouble(&value) else { return nil }
        return value
    }

    // Convenience method to advance the location of the scanner up to the first digit. Returning the scanner itself or nil, which allows for optional chaining
    func scanUpToNumber() -> Scanner? {
        var value: NSString?
        guard scanUpToCharacters(from: CharacterSet.decimalDigits, into: &value) else { return nil }
        return self
    }
}

let scanner = Scanner(string: string)
scanner.locale = Locale(identifier: "fr_FR")
let double = scanner.scanUpToNumber()?.scanDouble() // -> double = 3.95 (note the type is Double?)

在这些情况下,扫描仪比NSRegularExpressions更容易使用。