Regex,正則
參考網址:
http://deerchao.net/tutorials/regex/regex.htm
匹配字元:
[]-----表示匹配一個字元
^-----匹配字串的開始,如果不在[]裡面表示以什麼開頭, 在[^]表示不是那些字元
$-----匹配字串的結束
.-----點表示匹配除分行符號之外的任一字元
匹配字元取反:
\W-----匹配非(字母 或 數字 或 底線 或 漢字)
\w-----匹配(字母 或 數字 或 底線 或 漢字)
\D-----匹配非(數字字元)
\d-----匹配(數字字元)
\S-----匹配非(空白字元)
\s-----匹配(空白字元)
匹配次數:
{n}-----指定出現的次數
{m,n}-----最少出現m次,最多出現n次
{m,}-----最少出現m次,最多無限次
?-----重複0次或1次
+-----重複1次或多次
*-----重複0次或多次
Regex樣本:
abc-----匹配abc
[a-z][0-9]-----包含一個小寫字母,後面必須跟一個0-9的數字
[a-zA-Z][0-9]或者[a-z,A-Z][0-9]-----逗號可寫可不寫,包含一個字母,後面必須跟一個0-9的數字
[a-zA-Z][0-9]{4,9}-----包含一個字母,後面跟上4-9個數字(數字範圍0-9)
^[1-9][0-9]{4,11}$-----QQ號碼匹配,以1-9的數字開頭,後面跟0-9(4-11個)的數字,一共5-12個數字,^表示開始匹配,$表示結束匹配
^1[3,5,7,8]\\d{9}$或者^1[3,5,7,8][0-9]{9}$-----手機號碼匹配,以13/15/17/18開頭,長度11的數字
^[^0-9]-----不能是數字開頭
1 class ViewController: UIViewController { 2 3 override func viewDidLoad() { 4 super.viewDidLoad() 5 regularExpressionDemo() 6 } 7 8 private func regularExpressionDemo() -> (){ 9 // 源字串10 let str = "中國中國abc23872367中國中國"11 12 // 根據Regex進行匹配13 // pattern:Regex14 // options:匹配選項,如忽略大小寫等,傳[]即可15 // range:匹配的範圍16 let matchResult = try! NSRegularExpression(pattern: "abc", options: []).matches(in: str, options: [], range: NSMakeRange(0, (str as NSString).length))17 18 // 遍曆匹配結果19 for match in matchResult{20 // 匹配的範圍21 let range = match.range22 23 // 根據匹配的範圍截取出合格字串24 let subText = (str as NSString).substring(with: range)25 26 print("匹配範圍:\(NSStringFromRange(range));截取的字串:\(subText)")27 }28 }29 }