IPhone SDK4.0 regular expressions are the content to be introduced in this article.Regular ExpressionFor more information, see the details. The iPhone program uses regular expressions, mainly used in the NSRegularExpression class. I don't need to talk about it anymore. I will use it below.Regular ExpressionCode to replace the text content:
- // Replace the tag in the html element <a href = "Xxxx"> Yyyy </a>.
- -(NSString *) removeTag :( NSString *) srcStr {NSError * error = nil;
- NSMutableString * dest = [NSMutableString stringWithCapacity: 0];
- NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern: @ "<a href = \". +? \ "> (. + ?) </A>"
- Options: NSRegularExpressionCaseInsensitive error: & error];
- NSRegularExpression * regex2 = [[NSRegularExpression alloc] initWithPattern :@"(? <=> ).*? (? = </A> )"
- Options: NSRegularExpressionCaseInsensitive error: nil];
- NSUInteger numberOfMatches = [regex numberOfMatchesInString: srcStr options: 0 range: NSMakeRange (0, [srcStr length])];
- If (numberOfMatches! = 0) {[dest appendString: srcStr];
- /* The following lines are a method call. If a method call is too long, I am not used to the Branch. Even if a method call is too long, there is a method definition as a parameter in this call, so ......). */
- [Regex enumerateMatchesInString: srcStr options: 0 range: NSMakeRange (0, [srcStr length])
- UsingBlock: ^ (NSTextCheckingResult * result, NSMatchingFlags flags, BOOL * stop)
- {NSString * resultString = [srcStr substringWithRange: [result range];
- NSString * link = [resultString substringWithRange: [[regex2 firstMatchInString: resultString options: 0
- Range: NSMakeRange (0, [resultString length])] range];
- [Dest replaceCharactersInRange: [result range] withString: link];
- }
- ];
- Return
- [Dest stringByReplacingOccurrencesOfString: @ "<br/>" withString: @ ""];
- } Else
- {Return [srcStr stringByReplacingOccurrencesOfString: @ "<br/>" withString: @ ""];
- }
- } // Call
- -(Void) viewDidLoad {NSLog ([self owned mselector: @ selector (removeTag :) withObject: @ "this is <a href = \" www.baidu.com \ "> a </a> test! "]);
- }
Output result:
- this is a test!
Summary: DetailsIPhone SDK4.0Regular ExpressionI hope this article will help you!