Hi i am Trying to Match Characters in Words Same as Email Search while Sending Emails. Where popover is shown. By Typing text, Text is Highlighted in Popover.
Anna Haro
anna-haro@mac.com
Hank M. Zakroff
hank-zakroff@mac.com
what is Tried is,
\bHa[\w-]*
Expecting Match as,
Anna Ha ro
anna-haro@mac.com
Ha nk M. Zakroff
ha nk-zakroff@mac.com
Here are the way that you can highlight search string from whole string.
Step 1
: Add following method. that is created NSRegularExpression
object for you.
- (NSRegularExpression *)regularExpressionWithString:(NSString *)string options:(NSDictionary *)options
{
// Create a regular expression
BOOL isCaseSensitive = [[options objectForKey:kRWSearchCaseSensitiveKey] boolValue];
BOOL isWholeWords = [[options objectForKey:kRWSearchWholeWordsKey] boolValue];
NSError *error = NULL;
NSRegularExpressionOptions regexOptions = isCaseSensitive ? 0 : NSRegularExpressionCaseInsensitive;
NSString *placeholder = isWholeWords ? @"\\b%@\\b" : @"%@";
NSString *pattern = [NSString stringWithFormat:placeholder, string];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:regexOptions error:&error];
if (error)
{
NSLog(@"Couldn't create regex with given string and options");
}
return regex;
}
Step 2 : Here are the code that highlight the find string from whole string.
// 4: Call the convenient method to create a regex for us with the options we have
NSRegularExpression *regex = [self regularExpressionWithString:searchString options:options];
// 5: Find matches
NSArray *matches = [regex matchesInString:visibleText options:NSMatchingProgress range:visibleTextRange];
// 6: Iterate through the matches and highlight them
for (NSTextCheckingResult *match in matches)
{
NSRange matchRange = match.range;
[visibleAttributedText addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:matchRange];
}
Edit :
Replace
NSString *placeholder = @"\\b%@";
With
NSString *placeholder = isWholeWords ? @"\\b%@\\b" : @"%@";
Hope this help you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.