输入框删除@*** [微笑] 正则匹配

///删除表情 @人字符
- (BOOL)deleteAtPeopleEmojiStringAction{

NSString *souceText = _chatToolView.inputTextView.text;

NSRange range = _chatToolView.inputTextView.selectedRange;

if (range.location == NSNotFound) {
range.location = _chatToolView.inputTextView.text.length;
}


if(range.length == 0 && range.location == 0){
return NO;
}
else if (range.length > 0 ) {
return YES;
} else  {
NSString * selectedString = [souceText substringToIndex:range.location];

NSString * unselectString = [souceText substringFromIndex:range.location];


if ([selectedString hasSuffix:@" "]) {

//正则匹配要替换的文字的范围
NSString *pattern = @"@[\\w\\s\\p{InCJKUnifiedIdeographs}-]{1,100}";

NSError *error = nil;

NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
if (!re) {
NSLog(@"%@", [error localizedDescription]);
}
NSArray *resultArray = [re matchesInString:selectedString options:0 range:NSMakeRange(0, selectedString.length)];

NSTextCheckingResult *checkingResult = resultArray.lastObject;


///删除@ 人
if (_chatToolView.atPeoples.count > 0) {
for (NSString *atString in _chatToolView.atPeoples) {

if ([selectedString hasSuffix:@" "]) {
if ([[souceText substringWithRange:checkingResult.range] isEqualToString:atString]) {

NSString *newText = [selectedString substringToIndex:selectedString.length - checkingResult.range.length];
[_chatToolView.atPeoples removeObject:atString];

_chatToolView.inputTextView.text = [NSString stringWithFormat:@"%@%@",newText,unselectString];

_chatToolView.inputTextView.selectedRange=NSMakeRange(newText.length,0);

return NO;
}
}
}

return YES;

}
else{
return YES;
}
}
else  if ([selectedString hasSuffix:@"]"]){
//正则匹配要替换的文字的范围
NSString *pattern = @"\\[[^ \\[\\]]+?\\]";

NSError *error = nil;

NSRegularExpression * re = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
if (!re) {
NSLog(@"%@", [error localizedDescription]);
}
NSArray *resultArray = [re matchesInString:selectedString options:0 range:NSMakeRange(0, selectedString.length)];

NSTextCheckingResult *checkingResult = resultArray.lastObject;
if(checkingResult){
///删除表情
NSString *newText = [selectedString substringToIndex:selectedString.length - checkingResult.range.length];

_chatToolView.inputTextView.text = [NSString stringWithFormat:@"%@%@",newText,unselectString];

_chatToolView.inputTextView.selectedRange=NSMakeRange(newText.length,0);
return NO;
} else {
return YES;
}
}
else {
return YES;
}
}
}


你可能感兴趣的:(输入框删除@*** [微笑] 正则匹配)