iOS regular expression

Posted by toxic_brain on Fri, 21 Jan 2022 11:50:11 +0100

preface

In the actual development, almost every APP will have the function of login and registration. During login and registration, it is necessary to verify whether the content entered by the user meets the requirements; Sometimes you even need to find and intercept a string that meets the requirements in the string. At this time, you need to use a regular expression. Regular expressions look very difficult and have no rules to follow. Personally, I don't think we need to study them in depth and understand what we often use in daily development!

What the hell is a regular expression?

Regular expression is to use "string" to describe a rule feature, and then verify whether another "string" conforms to this feature. Eg: the expression "ab +" describes the feature that the verification string contains a "a" and N (N > = 1) B, which is consistent with "ab", "abb" and "abbb".

What can regular expressions be used for?

1. Verify whether the string conforms to the specified characteristics, such as whether it is a legal email address;
2. It is used to find strings. It is more flexible and convenient to find strings that meet the specified characteristics from a long text, such as finding fixed strings;
3. String replacement is more powerful than ordinary replacement;

Metacharacter

Regular expression prediction consists of two basic character types: literal character and metacharacter
Metacharacters enable regular expressions to have processing power. The so-called metacharacters refer to those special characters with special significance in regular expressions, which can be used to specify the occurrence mode of their leading characters (i.e. characters in front of metacharacters) in the target object

Common metacharacters

Metacharacterdescribe
^Match input string start position
$End of matching input string
.Matches any character except newline
|or
,division
[]Including, the default length is one character
[0-9]Match numbers from 0 to 9
[a-z]Match lowercase letters
[A-Z]Match capital letters
[a-zA-Z]Match English letters
[a-zA-Z0-9]Match English alphanumeric
[^]Not included. The default length is one character
{n}Repeat n times
{n,}Repeat > = n times
{n,m}N < = number of repetitions < = m
*Number of repetitions > = 0
+Number of repetitions > = 1
?Number of repetitions: 0 or 1
\Escape character
\dMatch number
\wMatch letters, numbers, or underscores
\sMatch white space characters: space, tab, page feed, etc
\DMatch non numeric characters
\WMatch all non alphabetic, non numeric, non underscore characters
\SMatch non white space characters

Brief description

Question: [0-9] and \ d differences
\d matches Unicode. To filter numeric characters in various languages:
012345789٠١٣٤٥٦٧٨۰۱۲۳۴۶۷۸۹०१२३४५६७८९০১২৩৪৫৬৭৮৯੦੧੨੩੪੫੬੭੮੯૦૧૨૩૪૫૬૭૮૯୦୧୨୩୪୫୬୭୮୯௦௧௨௩௪௫௬௭௮௯౦౧౨౩౪౫౬౭౮౯೦೧೨೩೪೫೬೭೮೯൦൧൨൩൪൫൬൭൮൯๐๑๒๓๔๕๖๗๘๙໐໑໒໓໔໕໖໗໘໙༠༡༢༣༤༥༦༧༨༩၀၁၂၃၄၅၆၇၈၉០១២៣៤៥៦៧៨៩᠐᠑᠒᠓᠔᠕᠖᠗᠘᠙
[0-9] matches Arabic numerals: 0 1 2 3 4 5 6 7 8 9
In comparison, the matching efficiency of [0-9] is a little higher;

Give a simple example of how to use the above metacharacters

Regular matching of mobile phone number

  • 11 digit matching: ^ [0-9] {11} $, [0-9] represents Arabic numerals 0 ~ 9, {11} represents 11 repetitions;
  • 11 digits, the first digit is "1": ^ 1 [0-9] {10} $, 1 indicates that the starting position is "1", and [0-9] {10} indicates that the digits from 0 to 9 are repeated 10 times
  • 11 digits, the first digit is "1", the second digit is "3", "4", "5", "7", "8": ^ 1 [3 | 4 | 5 | 7 | 8] [0-9] {9} & 1 indicates that the first digit is 1, [3 | 4 | 5 | 7 | 8] indicates that the second digit is 3, 4, 5, 7 or 8, [0-9] {9} indicates that the number from 0 to 9 is repeated 9 times

Common regular expressions

  • ID card No.

NSString *regex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
  • English letter beginning

NSString *ZIMU = @"^[A-Za-z]+$";
  • e-mail address

NSString *regex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
  • phone number

/**
     * phone number
     * Mobile: 134 [0-8], 135136137138139150151157158159182187188
     * China Unicom: 130131132152155156185186
     * Telecom: 1331349153180189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     * China Mobile: China Mobile
     * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     * China Unicom
     * 130,131,132,152,155,156,185,186
     */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     * China Telecom: China Telecom
     * 133,1349,153,180,189
     */
    NSString * CT = @"^1((33|53|77|8[019])[0-9]|349)\\d{7}$";
    /**
     * Fixed line and PHS in mainland China
     * Area code: 01002002102202302405027028029
     * Number: seven or eight digits
     */
  • URL link

NSString *regex = @"http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&=]*)?";
  • passport

/** The first is a letter, followed by numbers
     
     P:P The beginning is an ordinary passport for business
     D:Diplomatic passports start with a D
     E: Ordinary passports with electronic chips begin with the word "E",
     S: Followed by 8-digit Arabic official passport
     G:Private passport G
     14: 
     15: 
     
     H:The HKSAR passport and the home return card held by Hong Kong citizens begin with H, followed by 10 digits
     M:The Macao SAR passport and the return card held by Macao citizens begin with M, followed by 10 digits
     */
    NSString *regex = @"^1[45][0-9]{7}|([P|p|S|s]\\d{7})|([S|s|G|g]\\d{8})|([Gg|Tt|Ss|Ll|Qq|Dd|Aa|Ff]\\d{8})|([H|h|M|m]\\d{8,10})$";
  • Car license plate number

NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
  • Verification Code

NSString *regex = @"^(\\d{6})";
  • user name

NSString *userNameRegex = @"^[A-Za-z0-9]{4,20}+$";
  • password

NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
  • Password strength

NSString *regex = @"^(?=.*\\d.*)(?=.*[a-zA-Z].*).{6,20}$";
  • nickname

NSString *nicknameRegex = @"([\u4e00-\u9fa5]{2,5})(&middot;[\u4e00-\u9fa5]{2,5})*";
  • Bank card No

NSString *regex = @"^(\\d{15,30})";
  • Last four digits of bank card number

NSString *regex = @"^(\\d{4})";
  • All English letters

NSString *reges = @"^[A-Za-z]+$";
  • All English capital letters

NSString *reges = @"^[A-Z]+$";
  • All English small letters

NSString *reges = @"^[a-z]+$";
  • All English alphanumeric

NSString *reges = @"^[A-Za-z0-9]+$";

Now let's talk about how to use these regular expressions in iOS developers:

1. Nspredicate (validation string):

// String to validate
    NSString *mobilePhone = @"13227008888";
    // Write a regular expression to verify whether mobilePhone is a mobile phone number
    NSString *regex = @"^1[3|4|5|7|8][0-9]{9}$";
    // Create a predicate object and set a conditional expression
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    // String judgment, and then BOOL value
    BOOL result = [predicate evaluateWithObject:mobilePhone];
    NSLog(@"result : %@",result ? @"Regular mobile phone number" : @"Validation failed");
    // result: regular mobile phone number

2.NSString string lookup

- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask;

NSRange range = [mobilePhone rangeOfString:regex options:NSRegularExpressionSearch];
    if (range.location != NSNotFound) {
        // find
        NSLog(@"%@",NSStringFromRange(range));
    }else{
        //not found
    }

3. Nsregularexpression (find string):

NSError *error;
    NSString *rangeRegex = @"[8]{4}";
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:rangeRegex options:0 error:&error];
    if (!error) {
        NSTextCheckingResult *match = [regular firstMatchInString:mobilePhone options:0 range:NSMakeRange(0, [mobilePhone length])];
        if (match) {
            NSString *result = [mobilePhone substringWithRange:match.range];
            NSLog(@"%@",result);
        }
    }else{
        NSLog(@"error -- %@",error);
    }

Conclusion

So far, we have basically mastered the use of all regular expressions in common development and how to use metacharacters to create a regular expression.
The relevant regular expressions in this article have been uploaded in GitHub, and you can use CocoaPods to search and import! Welcome to use!

pod search WYQRegexHelper

-> WYQRegexHelper (0.0.1)
   provide iOS Develop common regular expressions
   pod 'WYQRegexHelper', '~> 0.0.1'
   - Homepage: https://github.com/YongQiangWei/RegularExpressionTool
   - Source:   https://github.com/YongQiangWei/RegularExpressionTool.git
   - Versions: 0.0.1 [master repo]
(END)



Author: a programmer who likes to eat durian
Link: https://www.jianshu.com/p/7a0f164dfa95
Source: Jianshu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Topics: iOS