要检查UITextView
是否包含URL或者提取URL,可以使用正则表达式来匹配URL的模式。以下是实现这一功能的方法:
以下是使用Swift语言检查UITextView
是否包含URL并提取URL的示例代码:
import UIKit
func containsURL(text: String) -> Bool {
let urlPattern = "((https?|ftp)://)?(www\\.)?[a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)"
let regex = try! NSRegularExpression(pattern: urlPattern)
let range = NSRange(location: 0, length: text.utf16.count)
return regex.firstMatch(in: text, options: [], range: range) != nil
}
func extractURLs(text: String) -> [String] {
let urlPattern = "((https?|ftp)://)?(www\\.)?[a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)"
let regex = try! NSRegularExpression(pattern: urlPattern)
let range = NSRange(location: 0, length: text.utf16.count)
var urls: [String] = []
regex.enumerateMatches(in: text, options: [], range: range) { match, _, _ in
if let match = match {
let url = (text as NSString).substring(with: match.range)
urls.append(url)
}
}
return urls
}
// 示例使用
let textViewText = "这是一个包含URL的文本:https://example.com 和 http://another-example.com"
if containsURL(text: textViewText) {
print("包含URL")
let urls = extractURLs(text: textViewText)
print("提取到的URLs: \(urls)")
} else {
print("不包含URL")
}
通过上述方法和代码示例,可以有效地检查UITextView
中的URL并进行提取。
领取专属 10元无门槛券
手把手带您无忧上云