C++ 標準ライブラリ<regex>
C++ 標準ライブラリの<regex>ヘッダーファイルは正規表現の機能を提供し、開発者が非常に柔軟な方法で文字列を検索、置換、分割することを可能にします。正規表現は強力なテキスト処理ツールであり、データ検証、テキスト分析、パターンマッチングなどの分野で広く使用されています。
正規表現は、単一の文字列を使用して、特定の構文規則に適合する一連の文字列を記述・マッチさせるパターンです。C++では、正規表現は<regex>ライブラリによって実装されます。
C++11の<regex>で正規表現を使用する場合、文字列リテラル内のバックスラッシュをエスケープする必要があります\。つまり、二重バックスラッシュとして記述します。\\。
なぜ二重バックスラッシュにするのか?
C++コンパイラはまず文字列リテラルのエスケープ文字を処理し、正規表現エンジンは後で処理します。
例えば、あなたが\d+と書くと、コンパイラは\dを未知のエスケープ文字とみなしてエラーにするか、dに変わります。正しい書き方は\\d+です。コンパイラはまず\\に変換し\、正規表現エンジンは読み取ります\d。
C++11は生文字列(raw string)もサポートしており、二重バックスラッシュを回避でき、複雑な正規表現を書くのに非常に適しています:regex re(R"(\d+)"); // 原始字符串,不需要写 \\d
- R"(...)" の中身はエスケープ処理されません
- 複数層の \ を含む複雑な正規表現を書く場合に使用することをお勧めします
基本構文
正規表現の基本構成
- 文字クラス:例えば
[abc]は a、b、c のいずれか1文字にマッチすることを示します。 - 量指定子:例えば
*(0回以上)、+(1回以上)、?(0回または1回)。 - 境界マッチ:例えば
^(行頭)、$(行末)。 - グループ化:丸括弧
()を使用してグループを作成します。
C++ <regex>ライブラリの主要なクラスと関数
std::regex:正規表現オブジェクトを表します。std::regex_match:文字列全体が正規表現にマッチするかどうかを確認します。std::regex_search:文字列内で正規表現にマッチする部分を検索します。std::regex_replace:文字列内で正規表現にマッチする部分を置換します。std::sregex_iterator:すべてのマッチ項目を走査するためのイテレータです。
例
1. 全体マッチ:regex_match
例
#include <iostream>
#include <regex>
using namespace std;
int main() {
regex re("\\d+"); // 数字にマッチ
string s = "12345";
if (regex_match(s, re))
cout << "マッチ成功\n";
else
cout << "マッチ失敗\n";
}
#include <regex>
using namespace std;
int main() {
regex re("\\d+"); // 数字にマッチ
string s = "12345";
if (regex_match(s, re))
cout << "マッチ成功\n";
else
cout << "マッチ失敗\n";
}
出力結果:
マッチ成功
2. 文字列が正規表現にマッチするかどうかを確認
例
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main() {
string text = "Hello, World!";
regex pattern("^[a-zA-Z]+, [a-zA-Z]+!$");
if (regex_match(text, pattern)) {
cout << "The string matches the pattern." << endl;
} else {
cout << "The string does not match the pattern." << endl;
}
return 0;
}
#include <string>
#include <regex>
using namespace std;
int main() {
string text = "Hello, World!";
regex pattern("^[a-zA-Z]+, [a-zA-Z]+!$");
if (regex_match(text, pattern)) {
cout << "The string matches the pattern." << endl;
} else {
cout << "The string does not match the pattern." << endl;
}
return 0;
}
出力結果:
The string matches the pattern.
3. 文字列内のマッチ項目を検索
例
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main() {
string text = "123-456-7890 and 987-654-3210";
regex pattern("\\d{3}-\\d{3}-\\d{4}");
smatch matches;
while (regex_search(text, matches, pattern)) {
cout << "Found: " << matches[0] << endl;
text = matches.suffix().str(); // 残りの部分をさらに検索
}
return 0;
}
#include <string>
#include <regex>
using namespace std;
int main() {
string text = "123-456-7890 and 987-654-3210";
regex pattern("\\d{3}-\\d{3}-\\d{4}");
smatch matches;
while (regex_search(text, matches, pattern)) {
cout << "Found: " << matches[0] << endl;
text = matches.suffix().str(); // 残りの部分をさらに検索
}
return 0;
}
出力結果:
Found: 123-456-7890 Found: 987-654-3210
4. 文字列内のマッチ項目を置換
例
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main() {
string text = "Hello, World!";
regex pattern("World");
string replacement = "Universe";
string result = regex_replace(text, pattern, replacement);
cout << "Original: " << text << endl;
cout << "Modified: " << result << endl;
return 0;
}
#include <string>
#include <regex>
using namespace std;
int main() {
string text = "Hello, World!";
regex pattern("World");
string replacement = "Universe";
string result = regex_replace(text, pattern, replacement);
cout << "Original: " << text << endl;
cout << "Modified: " << result << endl;
return 0;
}
出力結果:
Original: Hello, World! Modified: Hello, Universe!
詳細はこちら
よく使うクラスと型
| 名前 | 説明 |
|---|---|
std::regex |
正規表現をコンパイルしたオブジェクト |
std::smatch |
std::stringマッチ結果 |
std::cmatch |
C文字列のマッチ結果 (const char*) |
std::sregex_iterator |
用std::stringのマッチイテレータ |
std::cregex_iterator |
C文字列用のマッチイテレータ |
std::syntax_option_type |
正規表現構文オプション |
std::match_flag_type |
マッチ制御フラグ |
よく使う関数
| 関数名 | 用途 | 戻り値 | 例 |
|---|---|---|---|
regex_match(s, re) |
文字列全体がマッチするかどうかを確認 | bool |
regex_match("123", re) |
regex_search(s, m, re) |
最初のマッチを検索 | bool |
regex_search(s, m, re) |
regex_replace(s, re, fmt) |
マッチ項目を置換 | string |
regex_replace(s, re, "#") |
smatchマッチ結果オブジェクト
| メンバー | 説明 | 例 |
|---|---|---|
m.str() |
マッチした全体の内容を返す | cout << m.str() |
m[i] |
i番目のキャプチャグループを返す | m[1].str() |
m.position() |
マッチの開始位置 | m.position(0) |
m.size() |
キャプチャグループの数 | m.size() |
m.empty() |
マッチが空かどうか | m.empty() |
よく使う正規表現構文
| 記号 | 意味 | 例 | ||
|---|---|---|---|---|
. |
任意の文字 | a.cマッチabc |
||
\d |
数字 | \d+ |
||
\w |
英数字とアンダースコア | \w+ |
||
\s |
空白文字 | \s+ |
||
^ |
先頭 | ^abc |
||
$ |
末尾 | xyz$ |
||
+ |
1回以上 | a+ |
||
* |
0回以上 | a* |
||
? |
0回または1回 | a? |
||
{n,m} |
n〜m回 | \d{2,4} |
||
() |
キャプチャグループ | (ab)+ |
||
[] |
文字セット | [A-Z] |
||
| ` | ` | 或 | `cat | dog` |
C++のソースコード文字列では記述する必要があります\\dではなく\d、なぜなら\エスケープが必要だからです。
典型的な使用例
例
#include <iostream>
#include <regex>
using namespace std;
int main() {
regex re("\\d+");
string s = "abc123def456";
// 最初のマッチを検索
smatch m;
if (regex_search(s, m, re))
cout << "最初のマッチ: " << m.str() << endl;
// すべてのマッチを走査
for (sregex_iterator it(s.begin(), s.end(), re), end_it; it != end_it; ++it)
cout << "マッチした: " << it->str() << endl;
// 置換
string result = regex_replace(s, re, "#");
cout << result << endl;
}
#include <regex>
using namespace std;
int main() {
regex re("\\d+");
string s = "abc123def456";
// 最初のマッチを検索
smatch m;
if (regex_search(s, m, re))
cout << "最初のマッチ: " << m.str() << endl;
// すべてのマッチを走査
for (sregex_iterator it(s.begin(), s.end(), re), end_it; it != end_it; ++it)
cout << "マッチした: " << it->str() << endl;
// 置換
string result = regex_replace(s, re, "#");
cout << result << endl;
}