Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use regular expressions in ios

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly shows you "regular expressions in ios how to use", the content is easy to understand, clear, hope to help you solve doubts, the following let Xiaobian lead you to study and learn "regular expressions in ios how to use" this article.

Application of regular expression in ios

What is a regular expression

Regular expression, also known as normal representation, is a logical formula for string manipulation. A regular expression can detect whether a given string conforms to the logic we define, or it can get the specific part we want from the string. It can quickly achieve complex control of strings in a very simple way.

II. Syntax of regular expressions

Look at an example of filtering 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 that the string can only contain > = 1 0-9 numbers. Isn't the syntax a little weird?

Let's put aside the syntax of regular expressions in iOS and introduce it with the popular regular expression syntax. (iOS syntax is the same as popular regular expression syntax, except in the handling of escaped characters (language classes are the same).

Syntax:

First, the special symbols'^ 'and' $'. Their function is to indicate the beginning and end of a string, respectively. Eg:

"^ one": represents all strings starting with "one" ("one cat", "one123",)

Similar to:-(BOOL) hasPrefix: (NSString *) aString

"a dog$": a string that ends with "a dog" ("it is a dog",)

Similar to:-(BOOL) hasSuffix: (NSString *) aString

"^ apple$": a string that starts and ends with "apple". This is the only ~

"banana": represents any string that contains "banana".

Similar to the new method of iOS8-(BOOL) containsString: (NSString *) aString, search for substrings.

'*','+ 'and'?' These three symbols represent the number of times one or N characters are repeated. They mean "no or more" ([0meme + ∞] rounded), "one or more" ([1jue + ∞] rounded), "no or once" ([0mem1] rounded). Here are a few examples:

"ab*": indicates that a string has an a followed by zero or more b ("a", "ab", "abbb",... )

"ab+": indicates that a string has an a followed by at least one b or more ("ab", "abbb",... )

"ab?": indicates that a string has an a followed by zero or a b ("a", "ab")

"bb $": indicates that there are zero or one a followed by one or more b ("b", "ab", "bb", "abb", … at the end of the string. ).

You can enclose ({}) in curly braces to indicate a specific scope of repetition. For example

"ab {4}": indicates that a string has an a followed by four b ("abbbb")

"ab {1,}": indicates that a string has an a followed by at least 1 b ("ab", "abb", "abbb", …)

"ab {3pr 4}": indicates that a string has an a followed by 3 to 4 b ("abbb", "abbbb").

So, "*" can be expressed as {0,}, and "+" can be expressed as {1,}, "?" It can be denoted by {0jue 1}.

Note: there can be no lower limit, but not no upper limit! For example, "ab {, 5}" is misspelled.

"|" means "or" operation:

"a | b": indicates that there is "a" or "b" in a string

"(a | bcd) ef": indicates "aef" or "bcdef"

"(a | b) * c": indicates a string of "a" and "b" mixed strings followed by a "c"

Square brackets "[]" means that among the many characters in parentheses, select the grammatical characters in the parentheses as a result, for example

"[ab]": indicates that a string has a "a" or "b" (equivalent to "a | b")

"[amurd]": 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": a number that is preceded by a

"[a-zA-Z0-9] $": indicates that a string ends with a letter or number.

"." Match any single character except "\ r\ n":

"a.[ a-z]": indicates that a string has an "a" followed by an arbitrary character and a lowercase letter

"^. {5} $": represents any string of length 5

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

"(.)\ 1": represents two consecutive identical characters.

"10\ {1re2\}": indicates that the number 1 is followed by one or two zeros ("10", "100").

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

Use'^'in square brackets to indicate unwanted characters.'^ 'should be in the first place in square brackets.

"@ [^ a-zA-Z] 4 @" means that letters should not appear in the 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]".

Write a regular expression in iOS and add an extra "\" when you encounter an escape character, for example:

All-digit character: @ "^\ d\ + $"

Third, regular expressions in iOS

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]);}

4. Regular expressions commonly used

The following red strings are commonly used regular expressions (the following regular expressions are from Baidu encyclopedia)

1. Verify the user name and password: "^ [a-zA-Z]\ w {5pm 15} $"

two。 Verify the phone number: ("^ (\ d {3pr 4} -)\ d {7pr 8} $")

Eg:021-68686868 0511-6868686

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

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

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

6. You can only enter a string of numbers and 26 letters: ("^ [A-Za-z0-9] + $")

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

8. Only the number "^ [0-9] * $" can be entered.

9. Only n-digit numbers can be entered: "^\ d {n} $".

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

11. You can only enter the number of mdistinct n digits: "^\\ d {mrecoery n} $".

twelve。 You can only enter zero and non-zero numbers: "^ (0 | [1-9] [0-9] *) $".

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

14. Only positive real numbers with 1 / 3 decimal places can be entered: "^ [0-9] + (\. [0-9] {1Magne3})? $".

15. You can only enter a positive integer that is not zero: "^\ +? [1-9] [0-9] * $".

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

17. Only characters of length 3 can be entered: "^. {3} $".

18. You can only enter a string of 26 letters: "^ [A-Za-z] + $".

19. You can only enter a string of 26 capital letters: "^ [Amurz] + $".

20. You can only enter a string of 26 lowercase letters: "^ [amurz] + $".

21. Verify that it contains characters such as ^% &',; =? $\ ":" [^% &',; =? $\ x22] + ".

twenty-two。 You can only enter Chinese characters: "^ [\ u4e00 -\ u9fa5] {0,} $".

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

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

25. Verify the 31 days of the month: "^ ((0? [1-9]) | (1 | 2) [0-9]) | 30 | 31) $" the correct format is; "01" ~ "09", "10" ~ "29" and "30" ~ "31".

twenty-six。 Get date regular expression:\ d {4} [year |\.]\ d {\ 1 -\ 12} [month |\.]\ d {\ 1 -\ 31} day?

Comment: can be used to match most of the year, month and day information.

twenty-seven。 Match double-byte characters (including Chinese characters): [^\ X00 -\ xff]

Note: can be used to calculate the length of a string (a double-byte character length meter 2 ~ ~ ASCII character counter 1)

twenty-eight。 A regular expression that matches a blank line:\ n\ s*\ r

Comment: can be used to delete blank lines

twenty-nine。 Regular expression that matches the HTML tag:] * >. *? |

Commentary: the version circulated on the Internet is too bad, the above one can only match part of it, and there is still nothing I can do about complex nested tags.

thirty。 Regular expression that matches the leading and trailing white space characters: ^\ s* |\ sblank $

Comment: a very useful expression that can be used to delete white space characters (including spaces, tabs, page feeds, etc.) at the beginning and end of a line

thirty-one。 Regular expression that matches the URL URL: [a-zA-z] +: / / [^\ s] *

Note: the function of the version circulated on the Internet is very limited, and the above version can basically meet the needs.

thirty-two。 Whether the matching account is legal (5-16 bytes are allowed at the beginning of the letter, and alphanumeric underscores are allowed): ^ [a-zA-Z] [a-zA-Z0-9 _] {4j 15} $

Comment: form validation is very useful

thirty-three。 Match Tencent QQ number: [1-9] [0-9]\ {4,\}

Note: Tencent QQ starts at 10000

thirty-four。 Match China Postal Code: [1-9]\\ d {5} (?!\ d)

Commentary: the postal code of China is 6 digits

thirty-five。 Match the 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 three regular expressions in iOS

I previously introduced the use of built-in regular expressions in iOS (portals) in my blog post, and then I found that there are actually three ways to match regular expressions in iOS. Now record them all here:

1. Using NSPredicate (predicate) matching

For example, match a valid mailbox:

NSString * email = @ "nijino_saki@163.com"; NSString * regex = @ "[A-Z0-9a SELF MATCHES.% stories -] + @ [A-Za-z0-9.-] +\. [A-Za-z] {2jue 4}"; NSPredicate * predicate = [NSPredicate predicateWithFormat:@ "SELF MATCHES% @", regex]; BOOL isValid = [predicate evaluateWithObject:email]

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

two。 Take advantage of rangeOfString:option: find directly

NSString * searchText = @ "/ / Do any additional setup after loading the view, typically from a nib."; NSRange range = [searchText rangeOfString:@ "(?: [^,]) *\." Options:NSRegularExpressionSearch]; if (range.location! = NSNotFound) {NSLog (@ "% @", [searchText substringWithRange:range]);}

Setting NSRegularExpressionSearch in options means that using regular expression matching will return the position of the first matching result.

3. Use regular expression classes

NSString * searchText = @ "/ / Do any 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 matching results.

The above is all the content of the article "how to use regular expressions in ios". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report