@k_katsumi さんが VerbalExpressions の Objective-C向けライブラリを公開。
VerbalExpressions とは元々 JavaScript由来のもので、メソッドチェーンを組み合わせて正規表現相当を表現するテクニックらしい。
本家にマージされたとのこと(祝)。
こんな感じで書ける。Objective-Cというよりは本家のJavaScriptっぽい書き方。ドット記法で引数を取る書き方が新鮮。こんな風に記述できるのか。
// Create an example of how to test for correctly formed URLs
VerbalExpressions *verEx = [VerbalExpressions instantiate:^(VerbalExpressions *ve) {
ve.startOfLine(YES)
.then(@"http")
.maybe(@"s")
.then(@"://")
.maybe(@"www")
.anythingBut(@" ")
.endOfLine(YES);
}];実装のポイントは Blocksをプロパティ定義しているところ。
@interface VerbalExpressions : NSObject @property (nonatomic, readonly) VerbalExpressions *(^startOfLine)(BOOL enable); @property (nonatomic, readonly) VerbalExpressions *(^endOfLine)(BOOL enable); @property (nonatomic, readonly) VerbalExpressions *(^find)(NSString *value); @property (nonatomic, readonly) VerbalExpressions *(^then)(NSString *value); @property (nonatomic, readonly) VerbalExpressions *(^maybe)(NSString *value); @property (nonatomic, readonly) VerbalExpressions *(^anything)(); @property (nonatomic, readonly) VerbalExpressions *(^anythingBut)(NSString *value);引数を取り、自身を返す Blocksをプロパティとして定義している。
そしてプロパティの実体を用意する。
- (VerbalExpressions *(^)(NSString *))maybe
{
return ^VerbalExpressions *(NSString *value) {
value = [self sanitize:value];
self.add([NSString stringWithFormat:@"(%@)?", value]);
return self;
};
}自身を返すことでメソッドチェーンを構成できる。- - - -
ドット記法で引数を渡す表現ができるとは。眼から鱗。
この発想は無かった。面白い。

