我们如何删除 swift 中除数字、点和冒号之外的所有字符?

How can we remove every characters other than numbers, dot and colon in swift?

我无法从 html 正文中获取字符串

<html><head>
<title>Uaeexchange Mobile Application</title></head><body>
<div id='ourMessage'>
    49.40:51.41:50.41       
</div></body></html>

我想获取包含 49.40:51.41:50.41 的字符串。我不想通过 string advance 或 index 来完成。我可以通过在 swift 中指定我只需要数字、点 (.) 和冒号 (:) 来获取此字符串吗?我的意思是一些数字和一些特殊字符?

我试过了

let stringArray = response.componentsSeparatedByCharactersInSet(
                    NSCharacterSet.decimalDigitCharacterSet().invertedSet)
                let newString = stringArray.joinWithSeparator("")
                print("Trimmed\(newString)and count\(newString.characters.count)")

但这显然也去掉了点和冒号。朋友们有什么建议吗?

您问题的简单答案是您需要包含“.”。 & ":" 在您要保留的集合中。

let response: String = "<html><head><title>Uaeexchange Mobile Application</title></head><body><div id='ourMessage'>49.40:51.41:50.41</div></body></html>"

var s: CharacterSet = CharacterSet.decimalDigits

s.insert(charactersIn: ".:")

let stringArray: [String] = response.components(separatedBy: s.inverted)

let newString: String = stringArray.joined(separator: "")

print("Trimmed '\(newString)' and count=\(newString.characters.count)") 
// "Trimmed '49.40:51.41:50.41' and count=17\n"

如果没有关于您的其他回应的更多信息,我真的无法给出更好的答案,但从根本上说,这不是一个好的解决方案。如果响应是

怎么办
<html><head><title>Uaeexchange Mobile Application</title></head><body>
     <div id='2'>Some other stuff: like this</div>
     <div id='ourMessage'>49.40:51.41:50.41</div>
</body></html>

使用 replace/remove 解决方案是一种 hack,而不是算法 - 它会一直有效,直到它不起作用。 我认为您可能应该寻找 <div id='ourMessage'> 并从那里阅读到下一个 <,但是同样,我们需要有关响应格式规范的更多信息。

我建议使用 HTML 解析器,不过这是一个使用正则表达式的简单解决方案:

let extractedString = response.replacingOccurrences(of: "[^\d:.]+", with: "", options: .regularExpression)

或者 positive 正则表达式搜索,代码更多但也更可靠:

let pattern = ">\s?([\d:.]+)\s?<"

let regex = try! NSRegularExpression(pattern: pattern)
if let match = regex.firstMatch(in: response, range: NSMakeRange(0, response.utf8.count)) {
    let range = match.rangeAt(1)
    let startIndex = response.index(response.startIndex, offsetBy: range.location)
    let endIndex = response.index(startIndex, offsetBy: range.length)
    let extractedString = response.substring(with: startIndex..<endIndex)
    print(extractedString)
}

虽然简单(否定)正则表达式搜索会删除所有与数字、点和冒号不匹配的字符,但肯定搜索还会考虑结束标记 (>) 和开始标记 (<)围绕所需结果,因此意外数字、点或冒号与模式不匹配。

你也可以用其他方式使用String.replacingOccurrences()方法,不用正则表达式,如下:

import Foundation
var response: String = "<html><head><title>Uaeexchange Mobile Application</title></head><body><div id='ourMessage'>49.40:51.41:50.41</div></body></html>"
let charsNotToBeTrimmed = (0...9).map{String([=10=])} + ["." ,":"] // you can add any character you want here, that's the advantage
for i in response.characters{
    if !charsNotToBeTrimmed.contains(String(i)){
        response = response.replacingOccurrences(of: String(i), with: "")
    }
}
print(response)

基本上,这会创建一个不应该被修剪的字符数组,如果一个字符不在那里,它会在 for-loop

中被删除

但是你必须被警告,你正在尝试做的事情并不完全正确......