27
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Obj-C で正規表現

Posted at

動作環境による制限があるけど、標準でも正規表現を使えるようになってたのでメモ

iOS 4.2 以上
Mac OS X 10.7 以上

NSRegularExpression


NSError* err = nil;
NSRegularExpression* regex = nil;

// 検索する文字列
NSString* string = @"abc-defg";

// 正規表現オブジェクト作成
regex = [NSRegularExpression regularExpressionWithPattern:@"\w+-(\w)"
			options:NSRegularExpressionCaseInsensitive
			error:&error];

// 比較
NSTextCheckingResult *match = [regex firstMatchInString:string
                                                options:0
                                                  range:NSMakeRange(0, string.length)];

if (match) {
	// マッチした時の処理
   NSRange matchRange = [match range]; // マッチした個数
   NSRange firstHalfRange = [match rangeAtIndex:1];
}

// Block を使う方法
__block NSUInteger count = 0;
[regex enumerateMatchesInString:string
						   options:0
							 range:NSMakeRange(0, [string length])
						usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop)
{
     NSRange matchRange = [match range];
     NSRange firstHalfRange = [match rangeAtIndex:1];
     NSRange secondHalfRange = [match rangeAtIndex:2];
     if (++count >= 100) *stop = YES;
}];

参考

27
27
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?