つるながの綴り方

ITインフラ系のネタやTips、趣味としているカーライフなどを中心に日頃メモしておきたいことをしたためています。

正規表現の使い方

my_strに正規表現を使って、文字を切り出したサンプル。パターン定義の(...)を:[match rangeAtIndex:何個目]]で抜ける。

NSRegularExpression *regexp =
     [NSRegularExpression regularExpressionWithPattern:@"^〒\\d{3}-\\d{4} (.+)" options:0 error:nil];
NSTextCheckingResult *match =
     [regexp firstMatchInString:my_str options:0 range:NSMakeRange(0, my_str.length)];
             
if(match.numberOfRanges > 0) //〒123-4567の場合
    my_str = [my_str substringWithRange:[match rangeAtIndex:1]];
    ....