An example of learning regular expressions

The article takes OC as an example. Regular expressions do not distinguish between languages, and the rules in the article are also common in other languages.

Recently, there is a requirement to match a special string in a string, the format is <at open_id="" user_id="">nickname</at>

The regularity I wrote is as follows:

NSString *Regex =@"<at open_id=\"\\w{16}\" user_id=\"\\w{32}\">.{1,10}</at>";

Step by step analysis, the first half of the format is fixed: <at open_id=\"\" Since the value of open_id is 16 digits or letters, \w means numbers or letters, so use \w{16}

"\" needs to be escaped in iOS, so one more\

In this way, in the same way, the user_id limit is 32 bits

Then there is the nickname, which may match between 1-10 digits. Use .{1,10}, where "." represents all characters

This will write out the complete expression

Test code:

NSString *str = @"你好瘦猪 <at open_id=\"02PZgYL03okoqnjE\" user_id=\"bf94c94235d311ea9c80acde48001122\">瘦猪</at>你好胖猴<at open_id=\"02PZgYL03okoqnjE\" user_id=\"bf94c94235d311ea9c80acde48001122\">胖猴</at>";

 method:

    NSError *error;
   NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:Regex
                                                                          options:NSRegularExpressionCaseInsensitive
                                                                            error:&error];
       // 执行匹配的过程
   NSArray *matches = [regex matchesInString:str
                                     options:NSMatchingReportCompletion
                                       range:NSMakeRange(0, [str length])];
   for (NSTextCheckingResult *match in matches) {
       NSLog(@"%@",[str substringWithRange:match.range]);
   }

result:

There are two elements in matches, the correct position is printed out.

You can basically write simple regular expressions after seeing this.

More rules are as follows:

The special symbols'^' and'$'. Their function is to point out the beginning and end of a string separately. If you find a substring from the entire string, you don't need these two rules. If you want to determine whether the complete string meets the rules, it will be used.

Match any character:.
Match letters and numbers: \w
match numbers: \d
match blank characters: \s

 

"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");

"A?b+$": Indicates that there are zero or one a followed by one or several b at the end of the string ("b", "ab", "bb", "abb",...).

"Ab{4}": Indicates that a string has an a followed by 4 b ("abbbb");

"Ab{1,}": Indicates that a string has an a followed by at least 1 b ("ab", "abb", "abbb",...);

"Ab{3,4}": Indicates that a string has an a followed by 3 to 4 bs ("abbb", "abbbb").

Then "*" can be represented by {0,}, "+" can be represented by {1,}, and "?" can be represented by {0, 1};

 

"|" Means "or" operation, which all graduates from junior high school know;

"A|b": Indicates that there is "a" or "b" in a string;

"(A|bcd)ef": means "aef" or "bcdef";

"(A|b)*c": means a string of "a" and "b" mixed with a "c";

 

The square brackets "[ ]" indicate the conditions that many characters in the brackets must meet, as follows:

"[Ad]": Indicates that a string contains one of lowercase'a' to'd' (equivalent to "a|b|c|d" or "[abcd]");

"^[a-zA-Z]": represents a string beginning with a letter;

"[0-9]a": means a number before a;

 

Remarks:

The above example uses the regular expression class (NSRegularExpression), which will return an array.

This method returns the position information of the first matching substring :

Get the position of the substring in the complete string that meets the regular expression rules:

    NSRange range = [str rangeOfString:Regex options:NSRegularExpressionSearch];
    if (range.location != NSNotFound) {
        NSLog(@"range :%@", [str substringWithRange:range]);
    }

Determine whether the complete string conforms to the regular expression method, and return the bool value:

- (BOOL)validateNumber:(NSString *) textString
{
 NSString* number=@"^[0-9]+$";
 NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
 return [numberPre evaluateWithObject:textString];
}

 

Pay attention to the IT aesthetics of the official account and get more interesting technologies

Guess you like

Origin blog.csdn.net/bitcser/article/details/105330136