iOS Regular expressions

Source: Internet
Author: User
Tags alphabetic character

1, Introduction:

In the project, regular use is common, such as login account and password (mobile number, mailbox, etc.). The method used is predicate object filtering:nspredicate.

2. What is a regular expression:

Regular expressions, also known as formal representations, are a logical formula for manipulating strings. A regular expression can detect whether a given string conforms to our defined logic, or we can get the specific part we want from a string. It can quickly achieve complex control of strings in a very simple way.

3. Syntax:

First, the special symbols ' ^ ' and ' $ '. Their role is to indicate the beginning and end of a string, respectively. Eg: "^one": denotes all strings starting with "one" ("One Cat", "one123″, ); similar to:-(BOOL) Hasprefix: (NSString *) astring; " A dog$ ": the string that ends with" a dog "(" It is a dog ", ); similar to:-(BOOL) Hassuffix: (NSString *) astring; " ^apple$ ": Indicates that the start and end are" apple "strings, this is the only ~;" Banana ": represents any string that contains" banana ". A new method similar to IOS8-(BOOL) containsstring: (NSString *) astring, searching for substrings. ' * ', ' + ' and '? ' These three symbols represent the number of occurrences of one or n characters. They mean "no or more" ([0,+∞] rounding), "one or more" ([1,+∞] rounding), "No or Once" ([0,1] rounding). Here are a few examples: "ab*": a string that has an a followed by 0 or several B ("a", "AB", "ABBB",...... "ab+": Indicates that a string has a followed by at least one B or more ("AB", "ABBB",...... ); "Ab?" : Indicates that a string has a followed by 0 or a B ("a", "AB"); "a?b+$": indicates that at the end of the string there are 0 or one a followed by one or several B ("B", "AB", "BB", "ABB",...... )。 can be enclosed in curly braces ({}), indicating a specific range of duplicates. For example "Ab{4}": Indicates that a string has a followed by 4 B ("abbbb"); "Ab{1,}": Indicates that a string has a followed by at least 1 B ("AB", "ABB", "ABBB",......) ; "ab{3,4}": Indicates that a string has a followed by 3 to 4 B ("abbb", "abbbb"). Then, "*" can be used {0,} to indicate, "+" can be used {1,}, "?" You can use {0,1} to note: There can be no lower bound, but there is no limit! For example, "ab{,5}" is the wrong wording "| "Represent" or "Action:" A|b ": Indicates that a string has" a "or" B ";" (A|BCD) EF ": means" AEF "or" Bcdef ";" (a|b) *c ": A String" a "" B "is followed by a" C ", and the square brackets" [] "means the parenthesesAmong the numerous characters in the 1-n, select the syntax-conforming character in parentheses as the result, for example "[AB]": Indicates that a string has a "a" or "B" (equivalent to "a|b"); "[A-d]": Indicates that a string contains a lowercase ' a ' to ' d ' of one (equivalent to "a|b|c|d "[ABCD]"); "^[a-za-z]": denotes a string that begins with a letter; "[0-9]a": A number preceded by a digit; "[a-za-z0-9]$": A string that ends with a letter or number. “.” Match any single character except \ r \ n: "A.[a-z]": Indicates that a string has a "a" followed by an arbitrary character and a lowercase letter; "^. {5}$ ": represents any 1 string of length 5;" \num "where num is a positive integer. Indicates that the characters before "\num" appear the same number, for example "(.) \1″: Represents two consecutive identical characters. "10\{1,2\}": Represents a number 1 followed by 1 or 2 0 ("10″," 100″). "0\{3,\}" indicates a number of at least 3 consecutive 0 ("000", "0000", ... )。 Use ' ^ ' in square brackets to denote unwanted characters, ' ^ ' should be the first in square brackets. "@[^a-za-z][email protected]" means that no letters should appear in two "@". It is also commonly used: "\d" matches a numeric character. equivalent to [0-9]. "\d" matches a non-numeric character. equivalent to [^0-9]. "\w" matches any word character that includes an underscore. Equivalent to "[a-za-z0-9_]". "\w" matches any non-word character. Equivalent to "[^a-za-z0-9_]". Write regular expressions in iOS, encounter escape characters, add a "\", for example: Full character: @ "^\\d\+$"

4, commonly used regular expressions are as follows: (email, phone number, ID card, password, nickname)

Mailbox + (BOOL) Validateemail: (NSString *) email{nsstring *emailregex = @ "[a-z0-9a-z._%+-][email protected][ A-za-z0-9.-]+\\. [A-za-z]    {2,4} ";    Nspredicate *emailtest = [Nspredicate predicatewithformat:@ "Self MATCHES%@", Emailregex];    return [Emailtest Evaluatewithobject:email];} Mobile number verification + (BOOL) Validatemobile: (NSString *) mobile{//Mobile phone number starts with 13, 15, 18, eight \d numeric characters nsstring *phoneregex = @ "^ ((13[0-9] )| (15[^4,\\d]) | (18[0,0-9]))    \\d{8}$ ";    Nspredicate *phonetest = [Nspredicate predicatewithformat:@ "Self MATCHES%@", Phoneregex];    return [Phonetest evaluatewithobject:mobile];} Vehicle Grade verification + (BOOL) Validatecarno: (NSString *) carno{nsstring *carregex = @ "^[\u4e00-\u9fa5]{1}[a-za-z]{1}[a-za-z_0-9]{4}    [a-za-z_0-9_\u4e00-\u9fa5]$];    Nspredicate *cartest = [Nspredicate predicatewithformat:@ "Self MATCHES%@", Carregex];    NSLog (@ "Cartest is%@", cartest);    return [Cartest Evaluatewithobject:carno];} Model + (BOOL) Validatecartype: (NSString *) cartype{nsstring *cartyperegex = @"^[\u4e00-\u9fff]+$";    Nspredicate *cartest = [Nspredicate predicatewithformat:@ "Self MATCHES%@", Cartyperegex];    return [Cartest Evaluatewithobject:cartype];}    User name + (BOOL) Validateusername: (NSString *) name{nsstring *usernameregex = @ "^[a-za-z0-9]{6,20}+$";    Nspredicate *usernamepredicate = [Nspredicate predicatewithformat:@ "Self MATCHES%@", Usernameregex];    BOOL B = [Usernamepredicate evaluatewithobject:name];    return B;}    Password + (BOOL) ValidatePassword: (NSString *) password{nsstring *passwordregex = @ "^[a-za-z0-9]{6,20}+$";    Nspredicate *passwordpredicate = [Nspredicate predicatewithformat:@ "Self MATCHES%@", Passwordregex];    return [Passwordpredicate Evaluatewithobject:password];}    Nickname + (BOOL) Validatenickname: (NSString *) nickname{nsstring *nicknameregex = @ "^[\u4e00-\u9fa5]{4,8}$";    Nspredicate *passwordpredicate = [Nspredicate predicatewithformat:@ "Self MATCHES%@", Nicknameregex];    return [Passwordpredicate evaluatewithobject:nickname];} IdentityCertificate number + (BOOL) Validateidentitycard: (NSString *) identitycard{BOOL flag;        if (identitycard.length <= 0) {flag = NO;    return flag; } nsstring *regex2 = @ "^ (\\d{14}|\\d{17}) (\\d|[    XX]) $ ";    Nspredicate *identitycardpredicate = [Nspredicate predicatewithformat:@ "Self MATCHES%@", Regex2]; return [Identitycardpredicate Evaluatewithobject:identitycard];}

Finally, enclose some meta-characters of the regular expression:

Metacharacters Describe
\ Marks the next character as a special character, or a literal character, or a backward reference, or an octal escape. For example, "\\n" matches \ n. "\ n" matches the line break. The sequence "\ \" matches "\" and "\ (" Matches "(".
^ Matches the starting position of the input string. If the multiline property of the RegExp object is set, ^ also matches the position after "\ n" or "\ r".
$ Matches the end position of the input string. If the multiline property of the RegExp object is set, $ also matches the position before "\ n" or "\ r".
* Matches the preceding sub-expression 0 or more times (greater than or equal to 0 times). For example, zo* can match "Z", "Zo" and "Zoo". * Equivalent to {0,}.
+ Matches the preceding subexpression one or more times (greater than or equal to 1 times). For example, "zo+" can Match "Zo" and "Zoo", but not "Z". + equivalent to {1,}.
? Matches the preceding subexpression 0 or one time. For example, "Do (es)?" You can match "do" in "do" or "does".?
N N is a non-negative integer. Matches the determined n times. For example, "o{2}" cannot match "O" in "Bob", but can match two o in "food".
{N,} N is a non-negative integer. Match at least n times. For example, "o{2,}" cannot match "O" in "Bob", but can match all o in "Foooood". "O{1,}" is equivalent to "o+". "O{0,}" is equivalent to "o*".
{N,m} Both M and n are non-negative integers, where n<=m. Matches at least n times and matches up to M times. For example, "o{1,3}" will match the first three o in "Fooooood". "o{0,1}" is equivalent to "O?". Note that there can be no spaces between a comma and two numbers.
? When the character immediately follows any other restriction (*,+,?,{n},{n,},{n,m}), the matching pattern is non-greedy. The non-greedy pattern matches the searched string as little as possible, while the default greedy pattern matches as many of the searched strings as possible. For example, for the string "Oooo", "o+?" A single "O" will be matched, and "o+" will match all "O".
. Point Matches any single character except for "\ r \ n". To match any character that includes "\ r \ n", use a pattern like "[\s\s]".
(pattern) Match pattern and get this match. The obtained matches can be obtained from the resulting matches collection, the Submatches collection is used in VBScript, and the $0...$9 property is used in JScript. To match the parentheses character, use "\ (" or "\").
(?:p Attern) Matches pattern but does not get a matching result, which means that this is a non-fetch match and is not stored for later use. This is used in the or character "(|)" It is useful to combine the various parts of a pattern. For example, "Industr (?: y|ies)" is a more abbreviated expression than "industry|industries".
(? =pattern) Positive pre-check to match the find string at the beginning of any string matching pattern. This is a non-fetch match, which means that the match does not need to be acquired for later use. For example, "Windows (? =95|98| nt|2000) "Can match" windows "in" Windows2000 ", but does not match" windows "in" Windows3.1 ". Pre-checking does not consume characters, that is, after a match occurs, the next matching search starts immediately after the last match, rather than starting with the character that contains the pre-check.
(?! Pattern Forward negation, matching the lookup string at the beginning of any mismatched pattern string. This is a non-fetch match, which means that the match does not need to be acquired for later use. For example, "Windows (?! 95|98| nt|2000) "Can match" windows "in" Windows3.1 ", but does not match" windows "in" Windows2000 ".
(? <=pattern) Reverse positive pre-check, similar to positive pre-check, just the opposite direction. For example, "(? <=95|98| nt|2000) Windows can match "Windows" in 2000Windows, but not "windows" in "3.1Windows".
(? <!pattern) Reverse negation is similar to positive negative pre-checking, except in the opposite direction. For example "(? <!95|98| nt|2000) Windows can match "Windows" in 3.1Windows, but not "windows" in "2000Windows".
X|y Match x or Y. For example, "Z|food" can match "Z" or "food". "(z|f) Ood" matches "Zood" or "food".
[XYZ] The character set is combined. Matches any one of the characters contained. For example, "[ABC]" can Match "a" in "plain".
[^XYZ] Negative character set. Matches any character that is not contained. For example, "[^ABC]" can match "Plin" in "plain".
[A-z] The character range. Matches any character within the specified range. For example, "[A-z]" can match any lowercase alphabetic character in the range "a" to "Z". Note: The range of characters can be represented only if the hyphen is inside a character group and appears between two characters; If the beginning of the character group is out, only the hyphen itself can be represented.
[^a-z] A negative character range. Matches any character that is not in the specified range. For example, "[^a-z]" can match any character that is not in the range "a" to "Z".
\b Matches a word boundary, which is the position between a word and a space. For example, "er\b" can Match "er" in "never", but cannot match "er" in "verb".
\b Matches a non-word boundary. "er\b" can Match "er" in "verb", but cannot match "er" in "Never".
\cx Matches the control character indicated by X. For example, \cm matches a control-m or carriage return. The value of x must be one of a-Z or a-Z. Otherwise, c is considered to be a literal "C" character.
\d Matches a numeric character. equivalent to [0-9].
\d Matches a non-numeric character. equivalent to [^0-9].
\f Matches a page break. Equivalent to \x0c and \CL.
\ n Matches a line break. Equivalent to \x0a and \CJ.
\ r Matches a carriage return character. Equivalent to \x0d and \cm.
\s Matches any whitespace character, including spaces, tabs, page breaks, and so on. equivalent to [\f\n\r\t\v].
\s Matches any non-whitespace character. equivalent to [^ \f\n\r\t\v].
\ t Matches a tab character. Equivalent to \x09 and \ci.
\v Matches a vertical tab. Equivalent to \x0b and \ck.
\w Matches any word character that includes an underscore. Equivalent to "[a-za-z0-9_]".
\w Matches any non-word character. Equivalent to "[^a-za-z0-9_]".
\xn Match N, where n is the hexadecimal escape value. The hexadecimal escape value must be two digits long for a determination. For example, "\x41" matches "A". "\x041" is equivalent to "\x04&1". ASCII encoding can be used in regular expressions.
\num Matches num, where num is a positive integer. A reference to the obtained match. For example, "(.) \1 "matches two consecutive identical characters.
\ n Identifies an octal escape value or a backward reference. n is a backward reference if \ n is preceded by at least one of the sub-expressions obtained. Otherwise, if n is the octal number (0-7), N is an octal escape value.
\nm Identifies an octal escape value or a backward reference. If at least NM has obtained a subexpression before \nm, then NM is a backward reference. If there are at least N fetches before \nm, then n is a backward reference followed by the literal m. If none of the preceding conditions are met, if both N and M are octal digits (0-7), then \nm will match the octal escape value nm.
\nml If n is an octal number (0-7) and both M and L are octal digits (0-7), the octal escape value NML is matched.
\un Match N, where N is a Unicode character represented by four hexadecimal digits. For example, \u00a9 matches the copyright symbol (&copy;).
\< \> The start (\<) and End (\>) of the matching word (word). For example, the regular expression \<the\> can match "the" in the string "for the wise", but cannot match "the" in the string "otherwise". Note: This meta-character is not supported by all software.
\( \) The expression between \ (and \) is defined as group, and the character that matches the expression is saved to a staging area (up to 9 in a regular expression), which can be referenced by a \1 to \9 symbol.
| Perform a logical or (or) operation on the two matching criteria. For example, the regular expression (Him|her) matches "It belongs to him" and "it belongs to her", but does not match "it belongs to them." Note: This meta-character is not supported by all software.
+ Match 1 or more of that character just before it. For example, the regular expression + + matches 9, 99, 999, and so on. Note: This meta-character is not supported by all software.
? Match 0 or 1 of that character just before it. Note: This meta-character is not supported by all software.
{i} {i,j} Matches the specified number of characters, which are defined in the expression preceding it. For example, the regular expression a[0-9]{3} can match the character "A" followed by a string of exactly 3 numeric characters, such as A123, A348, etc., but does not match A1234. A regular expression [0-9]{4,6} matches any 4, 5, or 6 consecutive digits

Original link

Http://www.cnblogs.com/XYQ-208910/p/6056646.html

GitHub recommendations

Github:https://github.com/xiayuanquan/xyqregexpattern

iOS Regular expressions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.