Application of regular expressions in iOS and the use and comparison of three regular expressions in iOS _ regular expressions

Source: Internet
Author: User
Tags numeric lowercase

Application of regular expressions in iOS

One, what is the regular expression

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

Second, the syntax of regular expressions

Look at an example of filtered pure numbers

-(BOOL) ValidateNumber: (NSString *) textstring


{nsstring* number=@ "^[0-9]+$";
 Nspredicate *numberpre = [nspredicate predicatewithformat:@ "SELF matches%@", number];
 return [Numberpre evaluatewithobject:textstring];
}

The following statement is a regular expression

@ "^[0-9]+$"

It represents a string containing only the number of >=1 0-9, does the syntax have some weird?

Let's put aside the syntax of regular expressions in iOS and introduce them in popular regular expression syntax. (iOS syntax is the same as popular regular expression syntax, except that the escape character is processed (the language class is the same))

Grammar:

First, special symbols ' ^ ' and ' $ '. Their role is to point out the beginning and end of a string, respectively. eg

"^one": represents all strings that start with "one" ("One Cat", "one123″, );

Similar to:-(BOOL) Hasprefix: (NSString *) astring;

"A dog$": A string that represents the end of "a Dog" ("It is a dog", );

Similar to:-(BOOL) Hassuffix: (NSString *) astring;

"^apple$": indicates that the beginning and end are "apple" strings, this is the only ~;

"Banana": Represents any string containing "banana".

A new method similar to IOS8-(BOOL) containsstring: (NSString *) astring, searching for substrings.

' * ', ' + ' and '? ' The three symbols that represent the number of occurrences of one or n characters. They represent "no or more" ([0,+∞] rounding), one or more ([1,+∞] rounding), no or once ([0,1] rounding). Here are a few examples:

"ab*" means that a string has one 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 0 or a B ("a", "AB");

"a?b+$": means that at the end of the string there are 0 or one followed by one or several B ("B", "AB", "BB", "ABB",...... )。

can be enclosed in curly braces ({}) to indicate a specific range of repetitions. For example

"Ab{4}": Indicates that a string has a followed 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 3 to 4 B ("abbb", "abbbb").

So, "*" can be represented by {0,}, "+" can be represented by {1,}, "?" can be represented by {0,1}

Note: There can be no lower limit, but no limit! For example, "ab{,5}" is the wrong notation.

| Represents the or action:

"A|b": means "a" or "B" in a string;

"(A|BCD) EF": means "AEF" or "bcdef";

"(a|b) *c": Represents a string of "a" "B" mixed strings followed by a "C";

The square brackets "[]" denote the number of characters in parentheses, selecting 1-n characters in parentheses as a result, such as

"[AB]": Indicates that a string has a "a" or "B" (equivalent to "a|b");

[A-d]: Indicates that a string contains one of the lowercase ' a ' to ' d ' (equivalent to "a|b|c|d" or "[ABCD]");

"^[a-za-z]": Represents a string that begins with a letter;

"[0-9]a": Indicates a digit before A;

[a-za-z0-9]$: Indicates that a string ends with a letter or a 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 strings of length 5;

"\num" where num is a positive integer. Represents the same number of characters before "\num", such as

“(.) \1″: Represents two consecutive identical characters.

"10\{1,2\}": Indicates that the number 1 followed by 1 or 2 0 ("10″," 100″).

"0\{3,\}" means that the number is at least 3 consecutive 0 ("000", "0000"). )。

Use ' ^ ' in square brackets to denote a character that does not want to appear, ' ^ ' should be first in square brackets.

"@[^a-za-z]4@" means that letters should not appear in two "@".

Also commonly used are:

"\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_]".

In iOS, write a regular expression, hit the escape character, and add a "\", for example:

Full character: @ "^\\d\+$"

 Third, the iOS is the expression of

1. Regular expressions are used with nspredicate, eg:

-(BOOL) ValidateNumber: (NSString *) textstring
{
 nsstring* number=@ "^[0-9]+$";
 Nspredicate *numberpre = [nspredicate predicatewithformat:@ "SELF matches%@", number];
 return [Numberpre evaluatewithobject:textstring];
}

 2.NSString method

-(Nsrange) rangeofstring: (NSString *) astring options: (nsstringcompareoptions) mask;

NSString *searchtext = @ "rangeofstring";
Nsrange range = [SearchText rangeofstring:@ "^[0-9]+$" options:nsregularexpressionsearch];
if (range.location!= nsnotfound) {
 NSLog (@ "range:%@", [SearchText Substringwithrange:range]);
}

  3. Regular expression class (Nsregularexpression)

NSString *searchtext = @ "You want to match"; 
Nserror *error = NULL;
Nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:@ "^[0-9]+$" options: Nsregularexpressioncaseinsensitive error:&error];
Nstextcheckingresult *result = [Regex firstmatchinstring:searchtext options:0 range:nsmakerange (0, [searchText length] )];
if (result) {
 NSLog (@ "%@", [SearchText SubstringWithRange:result.range]);
}

Iv. Common Regular Expressions

The following red strings are common regular expressions (the following regular expressions come from Baidu Encyclopedia)

1. Verify username and password: "^[a-za-z]\w{5,15}$"

2. Authentication Telephone Number: ("^ (\\d{3,4}-) \\d{7,8}$")

eg:021-68686868 0511-6868686;

3. Verify mobile phone number: "^1[3|4|5|7|8][0-9]\\d{8}$";

4. Verify the ID card number (15 digits or 18 digits): "\\d{14}[[0-9],0-9xx]";

5. Verify Email Address: ("^\\w+" ([-+.] \\w+) *@\\w+ ([-.] \\w+) *\.\\w+ ([-.] \\w+) *$ ");

6. Only strings consisting of numbers and 26 English letters can be entered: ("^[a-za-z0-9]+$");

7. Integer or decimal: ^[0-9]+ ([.] {0,1} [0-9]+) {0,1}$

8. Only numbers can be entered: "^[0-9]*$".

9. Only n digits can be entered: "^\\d{n}$".

10. You can enter at least n digits: "^\\d{n,}$".

11. Only m~n digits can be entered: "^\\d{m,n}$".

12. Only numbers starting with 0 and not 0 are: "^" (0|[ 1-9][0-9]*) $ ".

13. Only positive real numbers with two decimal digits are entered: ^[0-9]+ (. [ 0-9]{2})? $ ".

14. Only positive real numbers with 1~3 decimal digits are entered: "^[0-9]+" (\.[ 0-9]{1,3})? $ ".

15. Only nonzero positive integers can be entered: "^\+?" [1-9] [0-9]*$].

16. You can only enter a Non-zero negative integer: "^\-[1-9][]0-9″*$."

17. You can only enter characters with a length of 3: "^. {3}$ ".

18. Only a string of 26 English letters can be entered: "^[a-za-z]+$".

19. You can only enter a string consisting of 26 uppercase letters: "^[a-z]+$".

20. You can only enter a string consisting of 26 lowercase English letters: "^[a-z]+$".

21. Verify that there are ^%& ',; =?$\ ' characters: "[^%& ',; =?$\x22]+".

22. Only Chinese characters can be entered: "^[\u4e00-\u9fa5]{0,}$".

23. Verify URL: "^http://([\\w-]+\.) +[\\w-]+ (/[\\w-./?%&=]*)? $ ".

24. Verification of the 12 months of the year: "^ (0?[ 1-9]|1[0-2]) $ "The correct format is:" 01″~ "09″ and" 10″~ "12″.

25. Verification of the one-month 31-day: "^ (0?[ 1-9]) | ((1|2) [0-9]) |30|31) $ "01″~" 09″, "10″~" 29″ and "30" ~ "31" in the correct format.

26. Get date Regular expression: \\d{4}[year |\-|\.] \\d{\1-\12}[month |\-|\.] \\D{\1-\31} day?

Commentary: can be used to match most of the year's date information.

27. Match Double-byte characters (including Chinese characters): [^\x00-\xff]

Commentary: can be used to compute the length of a string (a double-byte character length meter 2,ascii 1 characters)

28. Regular expression matching blank line: \n\s*\r

Commentary: can be used to delete blank lines

29. Regular expression:< matching HTML tags (\s*?) [^>]*>.*?</>|<.*? />

Commentary: The online version is too bad, the above can only match the part of the complex nested tags still powerless

30. Regular expression matching the end to end whitespace character: ^\s*|\s*$

Commentary: A useful expression that can be used to delete white-space characters (including spaces, tabs, page breaks, and so on) at the end of a line at the beginning

31. Matching the URL of the regular expression: [a-za-z]+://[^\s]*

Commentary: Online circulation of the version of the function is very limited, which can meet the basic requirements

32. Match account number is legal (beginning of letter, allow 5-16 bytes, allow alphanumeric underline): ^[a-za-z][a-za-z0-9_]{4,15}$

Commentary: Form validation is useful

33. Matching Tencent QQ number: [1-9][0-9]\{4,\}

Commentary: Tencent QQ number starting from 10 000

34. Match China ZIP Code: [1-9]\\d{5} (?! \d)

Commentary: China postal code is 6 digits

35. Matching IP address: (2[0-4]\\d|25[0-5]|[ 01]?\\d\\d?) \.) {3} (2[0-4]\\d|25[0-5]| [01]?\\d\\d?].

The use and comparison of 3 kinds of regular expressions in iOS

Before I introduced posting in iOS with regular expressions (portal), I found that there are three ways to implement regular expression matching in iOS. Now record them all here:

1. Using nspredicate (predicate) matching

For example, to match a valid mailbox:

NSString *email = @ "nijino_saki@163.com"; 
nsstring *regex = @ "[a-z0-9a-z._%+-]+@[a-za-z0-9.-]+\\.[ a-za-z]{2,4} "; 
Nspredicate *predicate = [nspredicate predicatewithformat:@ "SELF matches%@", regex); 
BOOL isValid = [predicate evaluatewithobject:email];

predicate matching is more flexible, but it requires knowledge of predicates.

2. Using rangeofstring:option: Direct lookup

NSString *searchtext = @ "//do no additional setup after loading the view, typically from a nib."; 
Nsrange range = [SearchText rangeofstring:@] (?: [^,]) *\\. "Options:nsregularexpressionsearch]; 
if (range.location!= nsnotfound) { 
 NSLog (@ "%@", [SearchText Substringwithrange:range]); 
}

The options set Nsregularexpressionsearch means that a regular expression match is used to return the position of the first matching result.

3. Using Regular Expression Classes

NSString *searchtext = @ "//do no additional setup after loading the view, typically from a nib."; 
Nserror *error = NULL;
Nsregularexpression *regex = [Nsregularexpression regularexpressionwithpattern:@ "(?: [^,]) *\\." Options: Nsregularexpressioncaseinsensitive error:&error];
Nstextcheckingresult *result = [Regex firstmatchinstring:searchtext options:0 range:nsmakerange (0, [searchText length] )];
if (result) {
 NSLog (@ "%@\n", [SearchText SubstringWithRange:result.range]);
}

Using the system's regular expression class (Nsregularexpression) returns multiple results that match.

The above content is the whole content of this article, Hope everybody likes.

Related Article

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.