Regular Expression
参考文档:
只列出一些重点,官方文档貌似只有oc的版本的说明
匹配的结果由NSTextCheckingResult来表示
初始NSRegularExpression
一般如下:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b(a|b)(c|d)\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
swift版本
let regexOption: NSRegularExpression.Options = isCaseSensitive ? [] : .caseInsensitive
let pattern = isWholeWords ? "\\b\(searchString)\\b" : searchString
try self.init(pattern: pattern, options: regexOption)
查找UITextView中的文字,并高亮显示
func highlightText(_ searchText: String, inTextView textView: UITextView) {
let attributedText = textView.attributedText.mutableCopy() as! NSMutableAttributedString
// 创建NSRange,并移除高亮
let attributedTextRange = NSMakeRange(0, attributedText.length)
attributedText.removeAttribute(
NSAttributedString.Key.backgroundColor,
range: attributedTextRange)
// 创建正则表达式
if let searchOptions = self.searchOptions,
let regex = try? NSRegularExpression(options: searchOptions) {
let range = NSRange(textView.text.startIndex..., in: textView.text)
if let matches = regex?.matches(in: textView.text, options: [], range: range) {
// 遍历匹配的结果,添加黄色的背景
for match in matches {
let matchRange = match.range
attributedText.addAttribute(
NSAttributedString.Key.backgroundColor,
value: UIColor.yellow,
range: matchRange
)
}
}
}
textView.attributedText = (attributedText.copy() as! NSAttributedString)
}
替换字符串
func searchForText(_ searchText: String, replaceWith replacementText: String, inTextView textView: UITextView) {
if let beforeText = textView.text, let searchOptions = self.searchOptions {
let range = NSRange(beforeText.startIndex..., in: beforeText)
if let regex = try? NSRegularExpression(options: searchOptions) {
let afterText = regex?.stringByReplacingMatches(
in: beforeText,
options: [],
range: range,
withTemplate: replacementText
)
textView.text = afterText
}
}
}
验证数据,例如验证邮箱、电话等
func validate(string: String, withRegex regex: NSRegularExpression) -> Bool {
let range = NSRange(string.startIndex..., in: string)
let matchRange = regex.rangeOfFirstMatch(
in: string,
options: .reportProgress,
range: range
)
return matchRange.location != NSNotFound
}