Application example code of regular expression in IOS

Time:2021-12-16

preface

Sometimes we need to filter out the fields we need in a long piece of text, Or check whether the text meets the requirements (whether the text is an email, link, phone number or ID card), regular expressions are needed at this time. IOS has also added relevant classes to support the use of regular expressions. This paper introduces the use of IOS regular expressions in detail and shares them for your reference and learning. I won’t say more below. Let’s take a look at the detailed introduction together.

1、 Nsregularexpression

1. Creation of regular expression


+ (nullable NSRegularExpression *)regularExpressionWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error;

- (nullable instancetype)initWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error

Properties in this class

  • Pattern returns the regular expression pattern
  • Options returns the options used when creating regular expression options
  • Numberofcapturegroups returns the regular expression pattern

The enumeration types defined by options are as follows:

typedef NS_OPTIONS(NSUInteger, NSRegularExpressionOptions) {
 Nsregularexpressioncasesensitive = 1 < < 0, // case insensitive
 Nsregularexpressionallowcommentsandwhitespace = 1 < < 1, // ignore spaces and #-
 Nsregularexpressionignoremetacharacters = 1 < < 2, // integration
 Nsregularexpressiondotmatcheslineseparators = 1 < < 3, // match any characters, including line separators
 Nsregularexpressionanchorsmatchlines = 1 < < 4, // allow ^ and $at the beginning and end of the match
 Nsregularexpressionuseunixlineseparators = 1 < < 5, // (the entire lookup range is invalid)
 Nsregularexpressionuseunicode wordboundaries = 1 < < 6 // (the entire search range is invalid)
 };

2. Search string

//Enumeration allows block to process strings that match each regular expression
- (void)enumerateMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range usingBlock:(void (NS_NOESCAPE ^)(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL *stop))block;

//Returns an array containing all occurrences of a regular expression in a string
- (NSArray<NSTextCheckingResult *> *)matchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;

//Returns the number of matches within the specified range of the string
- (NSUInteger)numberOfMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;

//Returns the first occurrence within the specified range of a string.
- (nullable NSTextCheckingResult *)firstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;

//Returns the first matching range within the specified range of a string
- (NSRange)rangeOfFirstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;

Nsmatchingoptions are defined as follows:

typedef NS_OPTIONS(NSUInteger, NSMatchingOptions) {
 Nsmatchingreportprogress = 1 < < 0, / * block is called periodically in long-running matching operations*/
 NSMatchingReportCompletion = 1 "1, / * after completing any match, call Block once * /
 Nsmatchinganchored = 1 < < 2, / * specifies that the match is limited to the match at the beginning of the search scope*/
 Nsmatchingwithtransparentbounds = 1 < < 3, / * fixed matching can check the part of the string beyond the search range for such purposes as word boundary detection, lookahead, etc. This constant has no effect if the search scope contains the entire string*/
 Nsmatchingwithoutanchoringboundaries = 1 < < 4 / * specify ^ and $will not automatically match the beginning and end of the search range, but will still match the beginning and end of the entire string. This constant has no effect if the search scope contains the entire string*/
};

3. Replace string

//Returns a new string that matches the regular expression replaced by the template string
- (NSString *)stringByReplacingMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)templ;

//Returns the number of replacements
- (NSUInteger)replaceMatchesInString:(NSMutableString *)string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)templ;

//Custom replacement function
- (NSString *)replacementStringForResult:(NSTextCheckingResult *)result inString:(NSString *)string offset:(NSInteger)offset template:(NSString *)templ;

//Returns the template string by adding a backslash escape as needed to protect any characters that match the pattern metacharacters
+ (NSString *)escapedTemplateForString:(NSString *)string;

Use example

NSString *str = @"aabbcccdeaargdo14141214aaghfh56821d3gad4";
 NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"aa" options:NSRegularExpressionCaseInsensitive error:NULL];
 if (expression != nil) {
  //First group matched to
  NSTextCheckingResult *firstMatch = [expression firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
  NSRange range = [firstMatch rangeAtIndex:0];
  NSString *result = [str substringWithRange:range];
  Nslog (@ "matched first group:% @", result);
  //Number of matches
  NSInteger number = [expression numberOfMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
  Nslog (@ "matched number% LD", number);
  //All data assigned to
  NSArray *allMatch = [expression matchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
  for (int i = 0; i < allMatch.count; i ++) {
   NSTextCheckingResult *matchItem = allMatch[i];
   NSRange range = [matchItem rangeAtIndex:0];
   NSString *result = [str substringWithRange:range];
   Nslog (@ "matched data:% @", result);
  }
  //Match to the position of the first group
  NSRange firstRange = [expression rangeOfFirstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)];
  Nslog (@ "match to the first group position: start position% Lu -- length% Lu", (unsigned long) firstrange location,(unsigned long)firstRange. length);
  
  //Replace string
  NSString *resultStr = [expression stringByReplacingMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length) withTemplate:@"bbbb"];
  Nslog (@ "replaced string:% @", resultstr);
  
  NSInteger resultNum = [expression replaceMatchesInString:[str mutableCopy] options:NSMatchingReportProgress range:NSMakeRange(0, str.length) withTemplate:@"bbbb"];
  Nslog (@ "number of replacements;% LD", (long) resultnum);
 }

Print log:
2017-08-13 23:28:53.898 first group matched by nsregularexpressiondemo [82046:8220904]: AA
Number of matched nsregularexpressiondemo [82046:8220904] 3
Nsregularexpressiondemo [82046:8220904] matched data: AA
Nsregularexpressiondemo [82046:8220904] matched data: AA
Nsregularexpressiondemo [82046:8220904] matched data: AA
Nsregularexpressiondemo [82046:8220904] matches the position of the first group: start position 0 -- length 2
Nsregularexpressiondemo [82046:8220904] replaced string: bbbbcccdbbbbrgdo141414bbbghfh56821d3gad4
Nsregularexpressiondemo [82046:8220904] number of replacements; three

2、 String


//NSStringCompareOptions --> NSRegularExpressionSearch
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch locale:(nullable NSLocale *)locale

As can be seen from the API above, only the first group can be matched

Use example

NSString *str = @"aabbcccdeaargdo14141214aaghfh56821d3gad4";
 NSRange strMatchStr = [str rangeOfString:@"aa" options:NSRegularExpressionSearch];
 Nslog (@ "match to string position: start position% Lu -- length% Lu", (unsigned long) strmatchstr location,(unsigned long)strMatchStr. length)
Print log:
Nsregularexpressiondemo [82080:8224265] matches the position of the string: start position 0 -- length 2

3、 Predicate

Use example

NSString *str2 = @"aabbcc";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^aa(.)*cc$"];
 BOOL isMatch = [predicate evaluateWithObject:str2];
 Nslog (@ "matched result:% d", ismatch);
Print log:
Nsregularexpressiondemo [82679:8253019] matching result: 1

4、 Regular expression

You can refer to this article:https://www.jb51.net/article/73342.htm

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for everyone’s study or work. If you have any questions, you can leave a message. Thank you for your support for developeppaer.