簡単な使い方
簡単な使い方
下記に文字列中の正規表現にマッチした部分をすべて置換する典型的なコードを示します。
(OgreKitプロジェクトのRegular Expression Testも参照)
#import <OgreKit/OgreKit.h>
...中略...
OGRegularExpression *regex;
regex = [OGRegularExpression regularExpressionWithString:@"a[^a]*a"];
NSLog(@"%@", [regex replaceAllMatchesInString:@"alphabetagammadelta"
withString:@"(\\0)"]);
// 表示結果:(alpha)bet(aga)mm(adelta)
注意点
- (void)replaceTest
{
// デリゲートに処理を委ねた置換
OGRegularExpression*celciusRegex;
celciusRegex = [OGRegularExpression
regularExpressionWithString:@"([+-]?\\d+(?:\\.\\d+)?)C\\b"];
NSString *targetString = @"36.5C, 3.8C, -195.8C";
NSLog(@"%@", [celciusRegex replaceAllMatchesInString:targetString
delegate:self
replaceSelector:@selector(fahrenheitFromCelsius:contextInfo:)
contextInfo:nil]);
// 表示結果: 97.7F, 38.8F, -320.4F
}
// 摂氏を華氏に変換する。
- (NSString*)fahrenheitFromCelsius:(OGRegularExpressionMatch*)aMatch
contextInfo:(id)contextInfo
{
doublecelcius = [[aMatch substringAtIndex:1] doubleValue];
doublefahrenheit = celcius * 9.0 / 5.0 + 32.0;
// 置換した文字列を返す。nilを返した場合は置換を終了する。
return [NSString stringWithFormat:@"%.1fF", fahrenheit];
}
3. 文字列中の正規表現にマッチした部分すべてを置換する