Swift5.0|Swift5.0 用正则表达式检测文本中的网页链接
获取方法如下:
import UIKitclass ViewController: UIViewController {override func viewDidLoad() {
super.viewDidLoad()}override func touchesBegan(_ touches: Set, with event: UIEvent?) {
let content = "三端拿到了卡机:\nhttp://www.baidu.com\n这是网址案件来看受打击了卡机了,dkajskldla:\n ahjahdkjhakhttp://www.baidu.com87647826478\n876238ahdkjandkanlk\nhttp://www.taobao.com这是网址\"http://www.baidu.cn\n\"卡号的快捷键啊https://www.iconfont.cn/collections/detail?cid=2301da"cj_getContentUrl(content: content)
}fileprivate func cj_getContentUrl(content:String) {
// 获取链接
var content = content.replacingOccurrences(of: "\n", with: "")
content = (content.trimmingCharacters(in: .whitespaces))
let regulaStr = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"
// 创建正则表达式对象
guard let regex = try? NSRegularExpression(pattern: regulaStr, options: []) else {
return
}
// 匹配到的字符串的内容
let results = regex.matches(in: content, options: [], range: NSRange(location: 0, length: content.count))
// 遍历结果,获取结果[NSTextCheckingResult]
var urls = [String]()if results.count > 0 {
for result in results {
let str = (content as NSString).substring(with: result.range)
urls.append(str)
}
cj_createAlertVC(urls: urls)
}
print("\(urls)")
}fileprivate func cj_createAlertVC(urls:[String]) {guard urls.count > 0 else {return}
// 创建网址提示框
let alertVC = UIAlertController(title: "提示", message: "检测到\(urls.count)个链接", preferredStyle:.actionSheet)
for url in urls {
let urlAction = UIAlertAction(title: url, style: .default) { (action) in
// 这里实现连接的跳转操作}
alertVC.addAction(urlAction)
}
let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (action) in
}
alertVC.addAction(cancelAction)
self.present(alertVC, animated: true) {}
}}
【Swift5.0|Swift5.0 用正则表达式检测文本中的网页链接】Demo地址
推荐阅读
- Docker应用:容器间通信与Mariadb数据库主从复制
- JS中的各种宽高度定义及其应用
- 由浅入深理解AOP
- 【译】20个更有效地使用谷歌搜索的技巧
- 涉毒患者(新诗)
- 参保人员因患病来不及到指定的医疗机构就医,能否报销医疗费用()
- mybatisplus如何在xml的连表查询中使用queryWrapper
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决
- MybatisPlus使用queryWrapper如何实现复杂查询
- 标签、语法规范、内联框架、超链接、CSS的编写位置、CSS语法、开发工具、块和内联、常用选择器、后代元素选择器、伪类、伪元素。