IOS-NSRegularExpression: string to be segmented by regular expressions in ios
Socialization is more accepted by the society. When a social product is made, it will be displayed by @ others upon reply or forwarding. Click @ user to go to the user's introduction page, here, you must first create appropriate labels, such as: <at href = \ "jecky: // profile/239 \"> iJecky </at>. Then, when the client obtains the text, NSRegularExpression is used to separate strings. The following uses the Rich Text OHAttributedLabel for Demonstration:
Note: The contentLabel used in this article is of the OHAttributedLabel type.
Example:
NSString * atstring = @ "test ah <at href = \" jecky: // profile/239 \ "> iJecky </at> test ah ";
Split first:
NSMutableString * resultStr = [NSMutableStringstringWithCapacity: 0];
NSString * pattern = @ "<at href = \"(.*?) \ "> (.*?) </At> ";
NSRegularExpression * regex = [NSRegularExpressionregularExpressionWithPattern: patternoptions: 0 error: nil];
NSArray * matches = [regexmatchesInString: atstringoptions: 0 range: NSMakeRange (0, atstring. length)];
NSUInteger lastIdx = 0;
For (NSTextCheckingResult * matchin matches)
{
Nsange range = match. range;
If (range. location> lastIdx)
{
NSString * temp = [atstringsubstringWithRange: NSMakeRange (lastIdx, range. location-lastIdx)];
[ResultStr appendString: temp];
}
NSString * link = [atstringsubstringWithRange: [match rangeAtIndex: 1];
NSString * text = [atstring substringWithRange: [matchrangeAtIndex: 2];
NSString * atName = [NSStringstringWithFormat: @ "@ % @", text];
[ResultStr appendString: atName];
[MarkDic setObject: linkforKey: atName];
LastIdx = range. location + range. length;
}
If (lastIdx <atstring. length)
{
NSString * temp = [atstringsubstringFromIndex: lastIdx];
[ResultStr appendString: temp];
}
Self. contentLabel. text = resultStr;
Then displayed on contentLabel
NSRegularExpression * userRegex = [NSRegularExpressionregularExpressionWithPattern: @ "\ B @ \ w +" options: 0 error: nil];
NSMutableAttributedString * mas = [self. contentLabel. attributedTextmutableCopy];
[UserRegex enumerateMatchesInString: self. contentLabel. textoptions: 0
Range: NSMakeRange (0, self. contentLabel. text. length)
UsingBlock: ^ (NSTextCheckingResult * match, NSMatchingFlags flags, BOOL * stop ){
NSString * auser = [self. contentLabel. textsubstringWithRange: match. range];
NSString * atlink = [markDicobjectForKey: auser];
If (atlink ){
[Mas setLink: [NSURLURLWithString: [markDic objectForKey: auser] range: match. range]; // add it
}
}];
OHParagraphStyle * para = [ohparagraphstyledefaparparagraphstyle];
Para. firstLineHeadIndent = 0;
Para. headIndent = 5;
Para. tailIndent =-5;
Para. textAlignment = kCTTextAlignmentLeft;
[Mas setParagraphStyle: para];
[OHASBasicMarkupParserprocessMarkupInAttributedString: mas];
Self. contentLabel. attributedText = mas;