仅包含“0123456789”的字符串。

时间:2016-11-22 13:50:11

标签: ios swift replace

我想删除此列表中没有的每个字符:“0123456790。”来自一个字符串

我试过了:

let characters = NSCharacterSet(charactersIn: "0123456789.").inverted
string = string.replacingOccurrences(of: characters.allCharacters().description, with: "", options: .regularExpression)

extension CharacterSet {
    func allCharacters() -> [Character] {
        var result: [Character] = []
        for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
                    result.append(Character(uniChar))
                }
            }
        }
        return result
    }
}

5 个答案:

答案 0 :(得分:2)

使用部分代码:

let charactersSet = NSCharacterSet(charactersIn: "0123456789.").inverted

extension String {
    func allCharacters() -> String {
        return self.components(separatedBy: charactersSet).joined()
    }
}

答案 1 :(得分:2)

Swift 3

string = (string.components(separatedBy: NSCharacterSet(charactersIn: "0123456789.").inverted) as NSArray).componentsJoined(by: "")

答案 2 :(得分:1)

使用此扩展程序。

var c = F1()
c.call()

答案 3 :(得分:0)

这应该这样做

var newString = (origString.components(separatedBy: CharacterSet.decimalDigits.inverted) as NSArray).componentsJoined(byString: "").replacingOccurrences(of: ".", with: "", options: .literal, range: nil)

答案 4 :(得分:0)

你可以改变你的第一个正则表达式以包含9之后的空格:

在swift:

var str = "test Test 333 9599 999";
val strippedStr = str.stringByReplacingOccurrencesOfString("[^0-9 ]",   withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil);
// strippedStr = " 33 9599 999"

虽然这留下了领先的空间,但您可以应用空白修剪来处理:

strippedStr.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// strippedStr = "33 9599 999"