【问题标题】:In Swift, how to write the regular expression to remove URLs in a string?在 Swift 中,如何编写正则表达式来删除字符串中的 URL?
【发布时间】:2016-04-03 09:11:29
【问题描述】:

我正在尝试删除字符串中的任何 URL,并且有一个 SO answer 提供了在 PHP 中使用正则表达式的解决方案:

$regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@";
echo preg_replace($regex, ' ', $string);

我直接在 Swift 中尝试如下:

myStr.stringByReplacingOccurrencesOfString("@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@", withString: "", options: .RegularExpressionSearch)

但它显示了一些错误Invalid escape sequence in literal

如何在 Swift 中正确地做到这一点?

【问题讨论】:

  • 删除封闭的@ 和双反斜杠。我认为您也不需要传递任何选项,使用options: []
  • 您不能在字符串中使用 / 键。因为 / 破坏了字符串语法。我们使用 / 截取字符串引号并将一些值转换为字符串。例如:“年龄:\(18)”所以你不能以/字符开头。

标签: regex swift swift2


【解决方案1】:

如果您想在不使用正则表达式的情况下从字符串中删除 url,您可以使用以下代码:

import Foundation

extension String {
    func removingUrls() -> String {
        guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
            return self
        }
        return detector.stringByReplacingMatches(in: self,
                                                 options: [],
                                                 range: NSRange(location: 0, length: self.utf16.count),
                                                 withTemplate: "")
    }
}

【讨论】:

    【解决方案2】:

    首先,您需要对转义字符“\”进行转义,因此每个“\”都变为“\\”。其次,你错过了第四个参数,即“范围:”

    import Foundation
    
    let myStr = "abc :@http://apple.com/@ xxx"
    myStr.stringByReplacingOccurrencesOfString(
        "@(https?://([-\\w\\.]+[-\\w])+(:\\d+)?(/([\\w/_\\.#-]*(\\?\\S+)?[^\\.\\s])?)?)@", 
        withString: "", 
        options: .RegularExpressionSearch, 
        range: myStr.startIndex ..< myStr.endIndex
    )
    
    // result = "abc : xxx"
    

    【讨论】:

    猜你喜欢
    • 2017-08-24
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2019-08-18
    相关资源
    最近更新 更多