在Swift中,如何编写正则表达式来删除字符串中的URL?

时间:2016-04-03 09:11:29

标签: regex swift swift2

我正在尝试删除字符串中的任何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中正确执行?

2 个答案:

答案 0 :(得分:3)

首先,您需要转义转义字符" \",所以每个" \"成为" \\"。其次,你错过了第4个参数,即"范围:"

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"

答案 1 :(得分:2)

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

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: "")
    }
}