只使用快速代码我无法弄清楚如何采取"(555)555-5555"并只返回数值并得到" 5555555555"。我需要删除所有括号,空格和短划线。我能找到的唯一例子是Objective-C,他们似乎都使用.trim()方法。似乎swift没有这个方法,但它确实有.stringByTrimmingCharacters方法,但这似乎只是修剪数据之前和之后的空格。
答案 0 :(得分:78)
extension String {
var digits: String {
return components(separatedBy: CharacterSet.decimalDigits.inverted)
.joined()
}
}
答案 1 :(得分:47)
将字符串中的非数字字符拆分为数字数组,并将它们连接回字符串:
Swift 1:
let stringArray = origString.componentsSeparatedByCharactersInSet(
NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let newString = NSArray(array: stringArray).componentsJoinedByString("")
Swift 2:
let stringArray = origString.componentsSeparatedByCharactersInSet(
NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let newString = stringArray.joinWithSeparator("")
Swift 3& 4:强>
let newString = origString
.components(separatedBy:CharacterSet.decimalDigits.inverted)
.joined(separator: "")
答案 2 :(得分:19)
我喜欢正则表达式:
var s = "(555) 555-5555"
s = s.stringByReplacingOccurrencesOfString(
"\\D", withString: "", options: .RegularExpressionSearch,
range: s.startIndex..<s.endIndex)
答案 3 :(得分:9)
这是@ Tapani的Swift 2.0答案作为一个方便的String扩展,(长度属性不是解决方案的一部分,但我在示例中留下它因为它也很方便):
(s/validate...)
用法:
import Foundation
extension String {
var length : Int {
return self.characters.count
}
func digitsOnly() -> String{
let stringArray = self.componentsSeparatedByCharactersInSet(
NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let newString = stringArray.joinWithSeparator("")
return newString
}
}
答案 4 :(得分:4)
在Swift 4中,解决方案更加出色:
import Foundation
let sourceText = "+5 (555) 555-5555"
let allowedCharset = CharacterSet
.decimalDigits
.union(CharacterSet(charactersIn: "+"))
let filteredText = String(sourceText.unicodeScalars.filter(allowedCharset.contains))
print(filteredText) // +55555555555
答案 5 :(得分:2)
我有一个类似的问题,但我需要保留小数点。我调整了最佳答案:
extension String {
/// Returns a string with all non-numeric characters removed
public var numericString: String {
let characterSet = CharacterSet(charactersIn: "01234567890.").inverted
return components(separatedBy: characterSet)
.joined()
}
}
答案 6 :(得分:1)
您想要使用NSCharacterSet:
查看用于Swift和Obj-C实现的NSHipster链接: http://nshipster.com/nscharacterset/
类似的例子:
var string = " Lorem ipsum dolar sit amet. "
let components = string.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).filter({!isEmpty($0)})
string = join(" ", components)
参见: punctuationCharacterSet
说明
返回包含标点符号类别中字符的字符集。 非正式地,此集合是用于分隔脚本中语言单位的所有非空白字符的集合,例如句点,短划线,括号等。
@Tapani提出了一个很好的建议:
NSCharacterSet.decimalDigitCharacterSet().invertedSet
答案 7 :(得分:1)
xCode 8.2.1,Swift 3
从字符串
中删除字符集import Foundation
extension String {
private func removeCharacters(unicodeScalarsFilter: (UnicodeScalar) -> Bool) -> String {
let filtredUnicodeScalars = unicodeScalars.filter{unicodeScalarsFilter($0)}
return String(String.UnicodeScalarView(filtredUnicodeScalars))
}
private func removeCharacters(from charSets: [CharacterSet], unicodeScalarsFilter: (CharacterSet, UnicodeScalar) -> Bool) -> String {
return removeCharacters{ unicodeScalar in
for charSet in charSets {
let result = unicodeScalarsFilter(charSet, unicodeScalar)
if result {
return true
}
}
return false
}
}
func removeCharacters(charSets: [CharacterSet]) -> String {
return removeCharacters(from: charSets) { charSet, unicodeScalar in
!charSet.contains(unicodeScalar)
}
}
func removeCharacters(charSet: CharacterSet) -> String {
return removeCharacters(charSets: [charSet])
}
func onlyCharacters(charSets: [CharacterSet]) -> String {
return removeCharacters(from: charSets) { charSet, unicodeScalar in
charSet.contains(unicodeScalar)
}
}
func onlyCharacters(charSet: CharacterSet) -> String {
return onlyCharacters(charSets: [charSet])
}
}
let string = "23f45gdor#@%#i425v wer 24 1+DWEJwi 3u09ru49w*()9uE2R_)$I#Q)_ U383q04+RFJO{dgnkvlj b`kefl;nwdl qsa`WKFSA,.E"
print("original string: \(string)")
print("only .decimalDigits: \(string.onlyCharacters(charSet: .decimalDigits))")
print("only [.decimalDigits, .symbols]: \(string.onlyCharacters(charSets: [.decimalDigits, .symbols]))")
print("remove .decimalDigits: \(string.removeCharacters(charSet: .decimalDigits))")
print("remove [.decimalDigits, .symbols]: \(string.removeCharacters(charSets: [.decimalDigits, .symbols]))")
创建快速过滤器的一个小想法。这是上面编写的代码的扩展
extension String {
var onlyDigits: String {
return onlyCharacters(charSets: [.decimalDigits])
}
var onlyLetters: String {
return onlyCharacters(charSets: [.letters])
}
}
let string = "23f45gdor#@%#i425v wer 24 1+DWEJwi 3u09ru49w*()9uE2R_)$I#Q)_ U383q04+RFJO{dgnkvlj b`kefl;nwdl qsa`WKFSA,.E"
print("original string: \(string)")
print(".onlyDigits: \(string.onlyDigits)")
print(".onlyLetters: \(string.onlyLetters)")
答案 8 :(得分:0)
这是@Tapani Swift 3.2解决方案
let phno = contact.phoneNumbers[0].phoneNumber
let strarr = phno.components(separatedBy: NSCharacterSet.decimalDigits.inverted)
let newString = NSArray(array: strarr).componentsJoined(by: "")
print(newString)
答案 9 :(得分:0)
我找到了具有过滤功能的最佳解决方案。请看一下。
let string = "(555) 555-5555"
let onlyDigits = string.filter({ (char) -> Bool in
if Int("\(char)") != nil {
return true
}
else {
return false
}
})
答案 10 :(得分:0)
没有完全回答,但看起来像一个数字。 我使用URLComponents来构建url,因为它会自动去除括号和破折号:
var telUrl: URL? {
var component = URLComponents()
component.scheme = "tel"
component.path = "+49 (123) 1234 - 56789"
return component.url
}
然后
UIApplication.shared.open(telUrl, options: [:], completionHandler: nil)
呼叫 +49 123 123456789
答案 11 :(得分:0)
尝试一下:
let string = "(555) 555-5555"
let digitString = string.filter { ("0"..."9").contains($0) }
print(digitString) // 5555555555
添加扩展名:
extension String
{
var digitString: String { filter { ("0"..."9").contains($0) } }
}
print("(555) 555-5555".digitString) // 5555555555