Regular Expression, Regular Expression
Reference URL:
Http://deerchao.net/tutorials/regex/regex.htm
Matching characters:
[] ----- Indicates matching a character
^ ----- Match the start of a string. If it does not start with a character in [], [^] indicates that it is not the character.
$ ----- End of matching string
. ----- Point indicates matching any character except line break
Matching character inversion:
\ W ----- match non-(letters, numbers, underscores, or Chinese characters)
\ W ----- match (letters, numbers, underscores, or Chinese characters)
\ D ----- match non-(numeric characters)
\ D ----- match (number character)
\ S ----- match non-(blank characters)
\ S ----- match (blank characters)
Matching times:
{N} ----- specify the number of occurrences
{M, n} ----- appears at least m times and at most n times
{M ,}----- appear at least m times and at most unlimited times
? ----- Repeated 0 or 1 times
+ ----- Repeat once or multiple times
* ----- Repeated 0 or multiple times
Regular Expression example:
Abc ----- match abc
[A-z] [0-9] ----- contains a lowercase letter, followed by a 0-9 Number
[A-zA-Z] [0-9] or [a-z, A-Z] [0-9] ----- a comma can be written or not, containing a letter, it must be followed by a 0-9 number.
[A-zA-Z] [0-9] {} ----- contains a letter followed by 4-9 digits (the number range is 0-9)
^ [1-9] [0-9] {} $ ----- QQ number matching, starting with a number 1-9, followed by a number 0-9 (4-11, A total of 5-12 numbers. ^ indicates start matching, and $ indicates end matching.
^ 1 [,] \ d {9} $ or ^ 1 [,] [0-9] {9} $ ----- mobile phone number matching, number starting with 13/15/17/18 and ending with 11
^ [^ 0-9] ----- cannot start with a number
1 class ViewController: UIViewController {2 3 override func viewDidLoad () {4 super. viewDidLoad () 5 regularExpressionDemo () 6} 7 8 private func regularExpressionDemo ()-> () {9 // source string 10 let str = "China abc23872367 China" 11 12 // Match 13 // pattern: Regular Expression 14 // options: match options, such as case-insensitive, can be passed [] 15 // range: the matching range is 16 let matchResult = try! NSRegularExpression (pattern: "abc", options: []). matches (in: str, options: [], range: NSMakeRange (0, (str as NSString ). length) 17 18 // traverse the matching result 19 for match in matchResult {20 // The matching range 21 let range = match. range22 23 // extract the matching string based on the matching range. 24 let subText = (str as NSString ). substring (with: range) 25 26 print ("matching range: \ (NSStringFromRange (range); intercepted string: \ (subText)") 27} 28} 29}