你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS之— NSRegularExpression正則分割字符串

iOS之— NSRegularExpression正則分割字符串

編輯:IOS開發綜合

社交化越來為社會所接受,在做社會化產品時,在回復或者轉發時會@他人 展示出來,點擊@user 跳轉到該用戶的介紹頁面,這裡首先要制定恰當的標簽,比如:iJecky,然後客戶端拿到文本時,要用到NSRegularExpression分割string,下面以富文本OHAttributedLabel來演示:

說明:本文中用到的contentLabel為OHAttributedLabel類型

示例:

NSString *atstring = @"測試啊測試啊 iJecky 測試啊測試啊";


首先分割:

NSMutableString *resultStr = [NSMutableString stringWithCapacity:0];

NSString *pattern = @"(.*?)";

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];

NSArray *matches = [regex matchesInString:atstring options:0 range:NSMakeRange(0, atstring.length)];

NSUInteger lastIdx = 0;

for (NSTextCheckingResult* match in matches)

{

NSRange range = match.range;

if (range.location > lastIdx)

{

NSString *temp = [atstring substringWithRange:NSMakeRange(lastIdx, range.location - lastIdx)];

[resultStr appendString:temp];

}

NSString *link = [atstring substringWithRange:[match rangeAtIndex:1]];

NSString *text = [atstring substringWithRange:[match rangeAtIndex:2]];

NSString *atName = [NSString stringWithFormat:@"@%@",text];

[resultStr appendString:atName];

[markDic setObject:link forKey:atName];

lastIdx = range.location + range.length;

}

if (lastIdx < atstring.length)

{

NSString *temp = [atstring substringFromIndex:lastIdx];

[resultStr appendString:temp];

}

self.contentLabel.text = resultStr;


然後展示到contentLabel上

NSRegularExpression* userRegex = [NSRegularExpression regularExpressionWithPattern:@"\\B@\\w+" options:0 error:nil];

NSMutableAttributedString* mas = [self.contentLabel.attributedText mutableCopy];

[userRegex enumerateMatchesInString:self.contentLabel.text options:0

range:NSMakeRange(0,self.contentLabel.text.length)

usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

NSString *auser = [self.contentLabel.text substringWithRange:match.range];

NSString *atlink = [markDic objectForKey:auser];

if (atlink) {

[mas setLink:[NSURL URLWithString:[markDic objectForKey:auser]] range:match.range]; // add it

}

}];

OHParagraphStyle* para = [OHParagraphStyle defaultParagraphStyle];

para.firstLineHeadIndent = 0;

para.headIndent = 5;

para.tailIndent = -5;

para.textAlignment = kCTTextAlignmentLeft;

[mas setParagraphStyle:para];

[OHASBasicMarkupParser processMarkupInAttributedString:mas];


self.contentLabel.attributedText = mas;





  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved