生文字列リテラル(Raw string literal)はNSStringのリテラルと組み合わせて使えるようです。@R”x(……)x“という記法でコンパイル・実行できました。

たとえばNSRegularExpressionと組み合わせると大変便利です。

extern "C"
{
#import <Foundation/Foundation.h>
}
#import <iostream>
 
int main()
{
  @autoreleasepool
  {
    auto s = @"テスト: http://example.com";
    NSError *error;
    // 以下は@"http://\\S+"と同じ
    auto regex = [NSRegularExpression
      regularExpressionWithPattern:@R"re(http://\S+)re"
                           options:0
                             error:&error];
    if (error == nil)
    {
      auto matchedRange = [regex
        rangeOfFirstMatchInString:s
                          options:0
                            range:NSRange{0, [s length]}];
      auto matchedString = [s substringWithRange:matchedRange];
      std::cout << matchedString.UTF8String << std::endl;
    }
  }
}
 
// 出力: http://example.com

この例だと大したことないと思われるかもしれませんが、\dや\sなどバックスラッシュの数が多くなってくると見通しの良さがよりはっきりすると思います。

そこだけObjective-C++を使う

「これだけのためにObjective-C++にするのはちょっと……」と思うのであれば、定数(NSString* const)に出すという手が考えられます。#defineなどではなくNSString* constの方式で定数を定義するなら、その定義を行うファイルだけ.mmにしてしまおうというわけです。

// Constants.h
 
#ifdef __cplusplus
extern "C" {
#endif
 
extern NSString* const HogeHogeRegurarExpression;
 
#ifdef __cplusplus
}
#endif
 
// Constants.mm
#import "Constants.h"
 
extern NSString* const HogeHogeRegurarExpression = R"re(……)re";

これで他のソースコードはObjective-C (*.m)のまま生文字列リテラルの効果を享受できます。


スポンサード リンク

この記事のカテゴリ

  • ⇒ @R”x(……)x”で生文字列リテラルによるNSString
  • ⇒ @R”x(……)x”で生文字列リテラルによるNSString