C++11で正規表現を扱うregex

regex.png

C++11の機能 regex

新しく正規表現を扱うクラスができたそうですよ!

#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main ()
{
  string s ("this subject has a submarine as a subsequence");
  regex e ("\\b(sub)([^ ]*)");   // subで始まる単語を探せ
  cout<<"入力文字列"<<s<<endl;
  cout<<"正規表現:"<<"\\b(sub)([^ ]*)"<<endl;
  // default constructor = end-of-sequence:
  regex_token_iterator<string::iterator> rend;
 
  cout << "完全一致:"; 
  regex_token_iterator<string::iterator> a ( s.begin(), s.end(), e );
  while (a!=rend) cout << " [" << *a++ << "]";
  cout << endl;
 
  cout << "のうち、subを抜いて出力する:";
  regex_token_iterator<string::iterator> b ( s.begin(), s.end(), e, 2 );
  while (b!=rend) cout << " [" << *b++ << "]";
  cout << endl;
 
  cout << "sub とそうでないの分けて表示:";
  int submatches[] = { 1, 2 };
  regex_token_iterator<string::iterator> c ( s.begin(), s.end(), e, submatches );
  while (c!=rend) cout << " [" << *c++ << "]";
  cout << endl;
 
  cout << "subじゃないやつの表示:";
  regex_token_iterator<string::iterator> d ( s.begin(), s.end(), e, -1 );
  while (d!=rend) cout << " [" << *d++ << "]";
  cout << endl;
 
  return 0;
}

出力結果
F:\sandbox>main.exe
入力文字列this subject has a submarine as a subsequence
正規表現:\b(sub)([^ ]*)
完全一致: [subject] [submarine] [subsequence]
のうち、subを抜いて出力する: [ject] [marine] [sequence]
sub とそうでないの分けて表示: [sub] [ject] [sub] [marine] [sub] [sequence]
subじゃないやつの表示: [this ] [ has a ] [ as a ]

cplus11 regula-expression

サポートサイト Wikidot.com cplus11regula-expression