从swift中删除字符串中的所有非数字字符

时间:2016-04-13 09:28:27

标签: swift nscharacterset

我需要解析一些应该只是数值的未知数据,但可能包含空格或其他非字母数字字符。

在Swift中有这种新方法吗?我在网上找到的所有东西似乎都是旧C的做事方式。

我正在查看stringByTrimmingCharactersInSet - 因为我确信我的输入在字符串的开头或结尾只有空格/特殊字符。我可以使用任何内置字符集吗?或者我需要创建自己的?

我希望有stringFromCharactersInSet()这样的东西可以让我只指定有效字符

17 个答案:

答案 0 :(得分:112)

  

我希望有一些类似stringFromCharactersInSet()的东西,它允许我只指定要保留的有效字符。

您可以将trimmingCharactersinverted字符集一起使用,以从字符串的开头或结尾删除字符。在Swift 3及更高版本中:

let result = string.trimmingCharacters(in: CharacterSet(charactersIn: "01234567890.").inverted)

或者,如果您要删除字符串中任何位置的非数字字符(不仅仅是开头或结尾),您可以filter characters,例如let result = string.filter("01234567890.".contains) 。在Swift 4.2.1中:

####.##

或者,如果您只想匹配某种格式的有效字符串(例如if let range = string.range(of: "\\d+(\\.\\d*)?", options: .regularExpression) { let result = string[range] // or `String(string[range])` if you need `String` } ),则可以使用正则表达式。例如:

[s.upper() for s in fruits if 'a' in s]

这些不同方法的行为略有不同,因此它只取决于您正在尝试做的事情。如果需要十进制数或仅整数,请包含或排除小数点。有很多方法可以实现这一目标。

对于较旧的Swift 2语法,请参阅previous revision of this answer

答案 1 :(得分:31)

let result = string.stringByReplacingOccurrencesOfString("[^0-9]", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range:nil).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

Swift 3

let result = string.replacingOccurrences( of:"[^0-9]", with: "", options: .regularExpression)

您可以选择this answer

答案 2 :(得分:21)

我更喜欢this solution,因为我喜欢扩展,对我来说似乎更清洁。解决方案转载于此:

extension String {
    var digits: String {
        return components(separatedBy: CharacterSet.decimalDigits.inverted)
            .joined()
    }
}

答案 3 :(得分:11)

  

Swift 4

我发现只能从字符串中获取字母数字字符的好方法。 例如: -

func getAlphaNumericValue() {

    var yourString  = "123456789!@#$%^&*()AnyThingYouWant"

    let unsafeChars = CharacterSet.alphanumerics.inverted  // Remove the .inverted to get the opposite result.  

    let cleanChars  = yourString.components(separatedBy: unsafeChars).joined(separator: "")


    print(cleanChars)  // 123456789AnyThingYouWant

}

答案 4 :(得分:10)

使用filter函数和rangeOfCharacterFromSet

的解决方案
let string = "sld [f]34é7*˜µ"

let alphaNumericCharacterSet = NSCharacterSet.alphanumericCharacterSet()
let filteredCharacters = string.characters.filter {
  return  String($0).rangeOfCharacterFromSet(alphaNumericCharacterSet) != nil
}
let filteredString = String(filteredCharacters) // -> sldf34é7µ

要仅过滤数字字符,请使用

let string = "sld [f]34é7*˜µ"

let numericSet = "0123456789"
let filteredCharacters = string.characters.filter {
  return numericSet.containsString(String($0))
}
let filteredString = String(filteredCharacters) // -> 347

let numericSet : [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
let filteredCharacters = string.characters.filter {
  return numericSet.contains($0)
}
let filteredString = String(filteredCharacters) // -> 347

答案 5 :(得分:8)

您可以使用模式匹配运算符过滤字符串的UnicodeScalarView,将UnicodeScalar ClosedRange从0传递到9并使用生成的UnicodeScalarView初始化新的String:

extension String {
    private static var digits = UnicodeScalar("0")..."9"
    var digits: String {
        return String(unicodeScalars.filter(String.digits.contains))
    }
}

"abc12345".digits   // "12345"

编辑/更新:

Swift 4.2

extension RangeReplaceableCollection where Self: StringProtocol {
    var digits: Self {
        return filter(("0"..."9").contains)
    }
}

或作为变异方法

extension RangeReplaceableCollection where Self: StringProtocol {
    mutating func removeAllNonNumeric() {
        removeAll { !("0"..."9" ~= $0) }
    }
}

编辑/更新:

Swift 5•Xcode 10.2

在Swift5中,我们可以使用名为isNumber的新Character属性:

extension RangeReplaceableCollection where Self: StringProtocol {
    var digits: Self {
        return filter({ $0.isNumber })
    }
}
extension RangeReplaceableCollection where Self: StringProtocol {
    mutating func removeAllNonNumeric() {
        removeAll { !$0.isNumber }
    }
}

游乐场测试:

"abc12345".digits   // "12345"

var str = "123abc0"
str.removeAllNonNumeric()
print(str) //"1230"

答案 6 :(得分:4)

Swift 3,过滤除数字以外的所有内容

let myString = "dasdf3453453fsdf23455sf.2234"
let result = String(myString.characters.filter { String($0).rangeOfCharacter(from: CharacterSet(charactersIn: "0123456789")) != nil })
print(result)

答案 7 :(得分:4)

Swift 4

但是没有扩展或组件也没有读取的字符串也不会被读取。

let allowedCharSet = NSCharacterSet.letters.union(.whitespaces)
let filteredText = String(sourceText.unicodeScalars.filter(allowedCharSet.contains))

答案 8 :(得分:2)

Swift 3

extension String {
    var keepNumericsOnly: String {
        return self.components(separatedBy: CharacterSet(charactersIn: "0123456789").inverted).joined(separator: "")
    }
}

答案 9 :(得分:2)

Swift 4.2

let numericString = string.filter { (char) -> Bool in
    return char.isNumber
}

答案 10 :(得分:2)

你可以这样做......

let string = "[,myString1. \"" // string : [,myString1. " 
let characterSet = NSCharacterSet(charactersInString: "[,. \"")
let finalString = (string.componentsSeparatedByCharactersInSet(characterSet) as NSArray).componentsJoinedByString("") 
print(finalString)   
//finalString will be "myString1"

答案 11 :(得分:2)

Rob的第一个解决方案的问题是stringByTrimmingCharactersInSet只过滤字符串的末尾而不是整个过滤器,如Apple的文档中所述:

  

返回通过从接收器的两端移除给定字符集中包含的字符而生成的新字符串。

而是使用componentsSeparatedByCharactersInSet首先将所有未出现的字符集隔离到数组中,然后使用空字符串分隔符将它们连接起来:

"$$1234%^56()78*9££".componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "0123456789").invertedSet)).joinWithSeparator("")

返回123456789

答案 12 :(得分:1)

Swift 4

<强> String.swift

import Foundation

extension String {

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

    func removeCharacters(from: String) -> String {
        return removeCharacters(from: CharacterSet(charactersIn: from))
    }
}

<强> ViewController.swift

let character = "1Vi234s56a78l9"
        let alphaNumericSet = character.removeCharacters(from: CharacterSet.decimalDigits.inverted)
        print(alphaNumericSet) // will print: 123456789

        let alphaNumericCharacterSet = character.removeCharacters(from: "0123456789")
        print("no digits",alphaNumericCharacterSet) // will print: Vishal

答案 13 :(得分:1)

Swift 4.0版

extension String {
    var numbers: String {
        return String(describing: filter { String($0).rangeOfCharacter(from: CharacterSet(charactersIn: "0123456789")) != nil })
    }
}

答案 14 :(得分:1)

CSSObject

CSS

答案 15 :(得分:0)

Swift 3版本

extension String
{
    func trimmingCharactersNot(in charSet: CharacterSet) -> String
    {
        var s:String = ""
        for unicodeScalar in self.unicodeScalars
        {
            if charSet.contains(unicodeScalar)
            {
                s.append(String(unicodeScalar))
            }
        }
        return s
    }
}

答案 16 :(得分:0)

Swift 4.2

let digitChars  = yourString.components(separatedBy:
        CharacterSet.decimalDigits.inverted).joined(separator: "")