swift中的t正則表達式
- 正則表達式是對字符串操作的一種邏輯公式,用事先定義好的一些特定字符、及這些特定字符的組合,組成一個"規則字符串",這個"規則字符串"用來表達對字符串的一種過濾邏輯。
正則表達式的用處:
-
- 判斷給定的字符串是否符合某一種規則(專門用於操作字符串)
- 電話號碼,電子郵箱,URL...
- 可以直接百度別人寫好的正則
- 別人真的寫好了,而且測試過了,我們可以直接用
- 要寫出沒有漏洞正則判斷,需要大量的測試,通常最終結果非常負責
-
- 過濾篩選字符串,網絡爬蟲
-
- 替換文字,QQ聊天,圖文混排
語法規則
[xyz] 字符集合(x/y或z)
[a-z] 字符范圍
[a-zA-Z]
[^xyz] 負值字符集合 (任何字符, 除了xyz)
[^a-z] 負值字符范圍
[a-d][m-p] 並集(a到d 或 m到p)
. 匹配除換行符以外的任意字符
\w 匹配字母或數字或下划線或漢字 [a-zA-Z_0-9]
\s 匹配任意的空白符(空格、TAB\t、回車\r \n)
\d 匹配數字 [0-9]
^ 匹配字符串的開始
$ 匹配字符串的結束
\b 匹配單詞的開始或結束
\W 匹配任意不是字母,數字,下划線,漢字的字符[^\w]
\S 匹配任意不是空白符的字符 [^\s]
\D 匹配任意非數字的字符[^0-9]
\B 匹配不是單詞開頭或結束的位置
[^x] 匹配除了x以外的任意字符
[^aeiou] 匹配除了aeiou這幾個字母以外的任意字符
* 重復零次或更多次
+ 重復一次或更多次
? 重復零次或一次
{n} 重復n次
{n,} 重復n次或更多次
{n,m} 重復n到m次,
*? 重復任意次,但盡可能少重復
*+ 重復1次或更多次,但盡可能少重復
?? 重復0次或1次,但盡可能少重復
{n,m}? 重復n到m次,但盡可能少重復
{n,}? 重復n次以上,但盡可能少重復
使用過程
- 1、創建規則
- 2、創建正則表達式對象
- 3、開始匹配
代碼示例
private func check(str: String) {
// 使用正則表達式一定要加try語句
do {
// - 1、創建規則
let pattern = "[1-9][0-9]{4,14}"
// - 2、創建正則表達式對象
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
// - 3、開始匹配
let res = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count))
// 輸出結果
for checkingRes in res {
print((str as NSString).substringWithRange(checkingRes.range))
}
}
catch {
print(error)
}
}
// 匹配字符串中所有的符合規則的字符串, 返回匹配到的NSTextCheckingResult數組
public func matchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> [NSTextCheckingResult]
// 按照規則匹配字符串, 返回匹配到的個數
public func numberOfMatchesInString(string: String, options: NSMatchingOptions, range: NSRange) -> Int
// 按照規則匹配字符串, 返回第一個匹配到的字符串的NSTextCheckingResult
public func firstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSTextCheckingResult?
// 按照規則匹配字符串, 返回第一個匹配到的字符串的范圍
public func rangeOfFirstMatchInString(string: String, options: NSMatchingOptions, range: NSRange) -> NSRange
使用子類來匹配日期、地址、和URL
- 看官網文檔解釋,可以知道這個
NSDataDetector
主要用來匹配日期、地址、和URL。在使用時指定要匹配的類型
public class NSDataDetector : NSRegularExpression {
// all instance variables are private
/* NSDataDetector is a specialized subclass of NSRegularExpression. Instead of finding matches to regular expression patterns, it matches items identified by Data Detectors, such as dates, addresses, and URLs. The checkingTypes argument should contain one or more of the types NSTextCheckingTypeDate, NSTextCheckingTypeAddress, NSTextCheckingTypeLink, NSTextCheckingTypePhoneNumber, and NSTextCheckingTypeTransitInformation. The NSTextCheckingResult instances returned will be of the appropriate types from that list.
*/
public init(types checkingTypes: NSTextCheckingTypes) throws
public var checkingTypes: NSTextCheckingTypes { get }
}
// 這個是類型選擇
public static var Date: NSTextCheckingType { get } // date/time detection
public static var Address: NSTextCheckingType { get } // address detection
public static var Link: NSTextCheckingType { get } // link detection
/**
匹配字符串中的URLS
- parameter str: 要匹配的字符串
*/
private func getUrl(str:String) {
// 創建一個正則表達式對象
do {
let dataDetector = try NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingType.Link.rawValue))
// 匹配字符串,返回結果集
let res = dataDetector.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count))
// 取出結果
for checkingRes in res {
print((str as NSString).substringWithRange(checkingRes.range))
}
}
catch {
print(error)
}
}
- ".*?" 可以滿足一些基本的匹配要求
- 如果想同時匹配多個規則 ,可以通過 "|" 將多個規則連接起來
- 將字符串中文字替換為表情
/**
顯示字符中的表情
- parameter str: 匹配字符串
*/
private func getEmoji(str:String) {
let strM = NSMutableAttributedString(string: str)
do {
let pattern = "\\[.*?\\]"
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive)
let res = regex.matchesInString(str, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, str.characters.count))
var count = res.count
// 反向取出文字表情
while count > 0 {
let checkingRes = res[--count]
let tempStr = (str as NSString).substringWithRange(checkingRes.range)
// 轉換字符串到表情
if let emoticon = EmoticonPackage.emoticonWithStr(tempStr) {
print(emoticon.chs)
let attrStr = EmoticonTextAttachment.imageText(emoticon, font: 18)
strM.replaceCharactersInRange(checkingRes.range, withAttributedString: attrStr)
}
}
print(strM)
// 替換字符串,顯示到label
emoticonLabel.attributedText = strM
}
catch {
print(error)
}
}
TextKit
給URL高亮顯示
- 主要用到三個類
NSTextStorage
NSLayoutManager
NSTextContainer
自定義UILabel來實現url高亮
/*
只要textStorage中的內容發生變化, 就可以通知layoutManager重新布局
layoutManager重新布局需要知道繪制到什么地方, 所以layoutManager就會文textContainer繪制的區域
*/
// 准們用於存儲內容的
// textStorage 中有 layoutManager
private lazy var textStorage = NSTextStorage()
// 專門用於管理布局
// layoutManager 中有 textContainer
private lazy var layoutManager = NSLayoutManager()
// 專門用於指定繪制的區域
private lazy var textContainer = NSTextContainer()
override init(frame: CGRect) {
super.init(frame: frame)
setupSystem()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSystem()
}
private func setupSystem()
{
// 1.將layoutManager添加到textStorage
textStorage.addLayoutManager(layoutManager)
// 2.將textContainer添加到layoutManager
layoutManager.addTextContainer(textContainer)
}
override func layoutSubviews() {
super.layoutSubviews()
// 3.指定區域
textContainer.size = bounds.size
}
override var text: String?
{
didSet{
// 1.修改textStorage存儲的內容
textStorage.setAttributedString(NSAttributedString(string: text!))
// 2.設置textStorage的屬性
textStorage.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(20), range: NSMakeRange(0, text!.characters.count))
// 3.處理URL
self.URLRegex()
// 2.通知layoutManager重新布局
setNeedsDisplay()
}
}
func URLRegex()
{
// 1.創建一個正則表達式對象
do{
let dataDetector = try NSDataDetector(types: NSTextCheckingTypes(NSTextCheckingType.Link.rawValue))
let res = dataDetector.matchesInString(textStorage.string, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, textStorage.string.characters.count))
// 4取出結果
for checkingRes in res
{
let str = (textStorage.string as NSString).substringWithRange(checkingRes.range)
let tempStr = NSMutableAttributedString(string: str)
// tempStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, str.characters.count))
tempStr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(20), NSForegroundColorAttributeName: UIColor.redColor()], range: NSMakeRange(0, str.characters.count))
textStorage.replaceCharactersInRange(checkingRes.range, withAttributedString: tempStr)
}
}catch
{
print(error)
}
}
// 如果是UILabel調用setNeedsDisplay方法, 系統會促發drawTextInRect
override func drawTextInRect(rect: CGRect) {
// 重繪
// 字形 : 理解為一個小的UIView
/*
第一個參數: 指定繪制的范圍
第二個參數: 指定從什么位置開始繪制
*/
layoutManager.drawGlyphsForGlyphRange(NSMakeRange(0, text!.characters.count), atPoint: CGPointZero)
}
獲取label中URL的點擊
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
// 1、獲取手指點擊的位置
let touch = (touches as NSSet).anyObject()!
let point = touch.locationInView(touch.view)
print(point)
// 2、獲取URL區域
// 注意: 沒有辦法直接設置UITextRange的范圍
let range = NSMakeRange(10, 20)
// 只要設置selectedRange, 那么就相當於設置了selectedTextRange
selectedRange = range
// 給定指定的range, 返回range對應的字符串的rect
// 返回數組的原因是因為文字可能換行
let array = selectionRectsForRange(selectedTextRange!)
for selectionRect in array {
if CGRectContainsPoint(selectionRect.rect, point) {
print("點擊了URL")
}
}
}