Skip to content

Instantly share code, notes, and snippets.

@katsuhide
Created August 16, 2013 16:23
Show Gist options
  • Save katsuhide/6251341 to your computer and use it in GitHub Desktop.
Save katsuhide/6251341 to your computer and use it in GitHub Desktop.
正規表現周り
// 文字列置換
NSString *string =@"hogehogehoge"; // 置換対象文字列
NSString *template = @"<br/>"; // 置換後文字列
NSString *replaced = [string stringByReplacingOccurrencesOfString:@"\n" withString:template];
// 文字列検索 <en-note>の開始位置を調べる
NSString *pattern = @"<en-note>";
NSRange rangeFrom = [content rangeOfString:pattern];
if(rangeFrom.location == NSNotFound){
return nil;
}
// 正規表現検索 <en-note>の開始位置を調べる
NSString *pattern = @"<en-note[^>]*>";
NSRange rangeFrom = [content rangeOfString:pattern options:NSRegularExpressionSearch];
if(rangeFrom.location == NSNotFound){
return nil;
}
// 正規表現検索
NSString *string = @"red. blue. <ss type> yellow. green. blue. </ss> black. white.<ss type> hoge </ss>aaaa";
NSError *error = nil;
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"<ss type>.+?</ss>" options:0 error:&error];
if (error != nil) {
NSLog(@"%@", error);
} else {
NSArray *matchs = [regexp matchesInString:string options:0 range:NSMakeRange(0, string.length)];
for(NSTextCheckingResult *match in matchs){
int count = (int)match.numberOfRanges;
for(int i = 0; i < count; i++){
NSLog(@"%@", [string substringWithRange:[match rangeAtIndex:i]]);
}
}
}
// 正規表現置換
NSError *error = nil;
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"\\n" options:0 error:&error];
NSString *replaced = [regexp stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0,string.length) withTemplate:template];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment