【问题标题】:How can we remove every characters other than numbers, dot and colon in swift?我们如何快速删除除数字、点和冒号之外的所有字符?
【发布时间】:2017-04-08 07:08:34
【问题描述】:

我一直无法从 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 的字符串。我不想通过字符串提前或索引来做到这一点。我可以通过在swift中指定我只需要数字、点(.)和冒号(:)来获取这个字符串吗?我的意思是一些数字和一些特殊字符?

我试过了

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

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

【问题讨论】:

    标签: swift swift2


    【解决方案1】:

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

    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>
    

    对此使用替换/删除解决方案是一种技巧,而不是一种算法 - 它会一直有效,直到它不起作用。 我认为您可能应该寻找&lt;div id='ourMessage'&gt; 并从那里阅读到下一个&lt;,但同样,我们需要有关响应格式规范的更多信息。

    【讨论】:

    • let newString = stringArray.joined()
    • @LeoDabus 我尽可能多地使用了 OP 的代码,但你当然是正确的 - 不需要类型或不必要的空字符串参数。为了清楚起见,我只是添加了类型 - 我认为这是 SO 的好习惯。
    【解决方案2】:

    我建议使用 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)
    }
    

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

    【讨论】:

      【解决方案3】:

      你也可以用其他方式使用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($0)} + ["." ,":"] // 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中删除

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

      【讨论】:

      • 请注意,修剪您正在迭代的数组并不是最好的做法,我只是想向您展示之前答案的替代方案,顺便说一句,这很棒!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多