LoginSignup
12
18

More than 5 years have passed since last update.

C++11で正規表現(std::regex)を使う

Last updated at Posted at 2015-07-22

C++11で正規表現(std::regex)を使う

string型文字列に正規表現を適用する場合

正規表現

(例)「int」「double」「char[20]」などの文字列に対して、
(int)、(double)、(char)[(20)]のように、型名と配列数をサブグループとして取り出す正規表現

"(int|double|char)(\\[(\\d+)\\])?"

ややこしいのは"\\["、"\\d+"、"\\]"の部分。
C/C++の文字列でバックスラッシュ一文字を表現すると"\\"になり、
正規表現のメタ文字である'['をエスケープするためにこれを前に付けて
"\\["となっている。その他も同様。

C++11で追加された生文字列リテラル「R"(〜)"」を使うと次のようにも書ける。
https://ezoeryou.github.io/cpp-book/C++11-Syntax-and-Feature.xhtml#raw.string.literal

 R"((int|double|char)(\[(\d+)\])?)"

サンプルコード

#include <regex>
#include <iostream>

using std::string;
using std::cout;
using std::endl;

int
main(){
  string str[3] = {"int", "double[4]", "char[32]"}; // 対象文字列
  std::regex re("(int|double|char)(\\[(\\d+)\\])?"); // 正規表現
  std::smatch match; // string型の文字列に対するマッチング結果を格納するのがstd::smatch型

  for( int i = 0; i < 3; ++i ){
    if(regex_match(str[i], match, re)){ // regex_match()は正規表現にマッチすると1を返す
      cout << "matched: " ;
      for ( int j = 0; j < match.size(); ++j ){ // match.size()はサブグループの数+1を返す
        std::cout << match[j] << ":";
      }
      cout << endl;
    }
  }
  return 0;
}

コンパイル時は-std=c++11を忘れずに。

実行結果

matched: int:int:::
matched: double[4]:double:[4]:4:
matched: char[32]:char:[32]:32:

char *型文字列やワイド型文字列への正規表現の適用

以下のリンクが参考になる。
http://codezine.jp/article/detail/7716

12
18
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
12
18