2

我的代码片段是:

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 €” - 我想削减所有货币“£€₹”和“from”或“ab”之类的词

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

4

5 回答 5

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”。

于 2017-06-15T15:37:15.047 回答
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 更容易使用。

于 2017-06-15T14:42:41.990 回答
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)

...产生“28.50”。

于 2017-06-15T14:03:36.867 回答
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)
}
于 2017-06-15T14:26:18.660 回答
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)
}
于 2017-06-15T13:47:04.623 回答