Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 在Swift中,如何编写正则表达式来删除字符串中的URL?_Regex_Swift_Swift2 - Fatal编程技术网

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

Regex 在Swift中,如何编写正则表达式来删除字符串中的URL?,regex,swift,swift2,Regex,Swift,Swift2,我试图删除字符串中的任何URL,有一个在PHP中使用正则表达式的解决方案: $regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@"; echo preg_replace($regex, ' ', $string); 我直接在Swift中尝试: myStr.stringByReplacingOccurrencesOfString("@(https?://([-\w\.]+[-\w])+(:\

我试图删除字符串中的任何URL,有一个在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)
但是它在literal中显示了一些错误
无效的转义序列


如何在Swift中正确执行

首先,您需要转义转义字符“\”,因此每个“\”变为“\”。第二,您错过了第四个参数,即“范围”:

<代码>导入基础 让myStr=“abc:@http://apple.com/@xxx“ myStr.stringByReplacingOccurrencesOfString( “@(https?:/([-\\w\\.]+[-\\w])+(:\\d+)(/([\\w/\\\.\\\.\\.-]*(\\\?\\S+?[^\\\.\\S]))”, 带字符串:“”, 选项:。常规表达式搜索, 范围:myStr.startIndex..
如果要在不使用正则表达式的情况下从字符串中删除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: "")
    }
}

删除封闭的
@
和双反斜杠。我认为您也不需要传递任何选项,请使用
options:[]
您不能使用/输入字符串。因为/中断了字符串语法。我们使用/截取字符串引号,并将一些值转换为字符串。例如:“age:\(18)”所以不能以/character开头。我发现我可以直接从Java的答案中使用这些正则表达式:
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: "")
    }
}