Using Regular Expressions for Text Search and Replace
As noted in Chapter 8, the Cocoa Touch
NSString object does not offer a method
to perform search and replace operations with regular expressions (as the
JavaScript String object does).
Instead, you can use the iOS 4 (or later) NSRegularExpression class to do the job. To
demonstrate how this works, I’ll once again use the UITextField example from earlier in this chapter
as a basis. The goal of this version will be to strip out any extra spaces
between words entered into the text field and display the results in the
label below the field. Example 9-20 shows the one new
method and two modified methods from Example 9-18.
Example 9-20. Modifications for regular expression search and replace
- (NSString *)stripExtraWhitespace:(NSString *)inputString { NSString *result = inputString; // One or more whitespace characters NSString *whiteSpacePattern = @"\\s+"; NSString *replacementString = @" "; NSError *error = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:whiteSpacePattern options:0 error:&error]; if (regex == nil) { NSLog(@"RegExp Error: %@", [error localizedDescription]); } else { result = [regex stringByReplacingMatchesInString:inputString options:0 range:NSMakeRange(0, [inputString length]) withTemplate:replacementString]; } return result; } // UITextField delegate message - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } - (IBAction)copyInput:(id)sender ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access