- 追加された行はこの色です。
- 削除された行はこの色です。
第13回は正規表現になります。
※正規表現自体がわからない人は自分で調べるようにしてください。
C++11では正規表現を利用した文字列操作ができるようになりました。
1: #include <iostream>
2: #include <regex>
3: #include <string>
4:
5: using namespace std;
6:
7: int main()
8: {
9: //検索する文字列
10: string str{"aaaa aaab aabb abbb bbbb"};
11:
12: //正規表現
13: regex rex("\\b(aa)([^ ]*)");
14:
15: smatch m;
16:
17: while (regex_search(str, m, rex))
18: {
19: cout << m[0] << endl;
20: str = m.suffix().str();
21: }
22:
23: return 0;
24: }
このプログラムの実行結果は
aaaa
aaab
aabb
こうなります。
複雑なことも出来ます。
1: #include <iostream>
2: #include <regex>
3: #include <string>
4:
5: using namespace std;
6:
7: int main()
8: {
9: //検索する文字列
10: string str{"aaaa aaab aabb abbb bbbb"};
11:
12: //正規表現
13: regex rex("\\b(aa)([^ ]*)");
14:
15: regex_token_iterator<string::iterator> end;
16:
17: //完全一致
18: regex_token_iterator<string::iterator> match1{ str.begin(), str.end(), rex };
19: while (match1 != end)
20: {
21: cout << *match1++ << endl;
22: }
23: cout << endl;
24:
25: //正規表現に一致した中から正規表現部分以外を表示
26: regex_token_iterator<string::iterator> match2{ str.begin(), str.end(), rex, 2 };
27: while (match2 != end)
28: {
29: cout << *match2++ << endl;
30: }
31: cout << endl;
32:
33: //正規表現に一致した中から正規表現部分と以外のを分けて表示
34: regex_token_iterator<string::iterator> match3{ str.begin(), str.end(), rex, {1, 2} };
35: while (match3 != end)
36: {
37: cout << *match3++ << endl;
38: }
39: cout << endl;
40:
41: //正規表現に一致しなかったのを表示
42: regex_token_iterator<string::iterator> match4{ str.begin(), str.end(), rex, -1 };
43: while (match4 != end)
44: {
45: cout << *match4++ << endl;
46: }
47: cout << endl;
48:
49: return 0;
50: }
・結果
aaaa
aaab
aabb
aa
ab
bb
aa
aa
aa
ab
aa
bb
abbb bbbb
※妙な空白があるのは正規表現で空白のみを検索したのがあるためです。
正規表現を利用して検索した文字列はそのまま個々の文字列として扱うことが可能です。
大量の文章の変換処理などを作成するとき等に便利だと思います。
以上で正規表現の説明を終わります。
前→C++11講座12回
次→C++11講座14回
#vote(野[0],田[0],内閣[0])