ポイント
- 文字のパターン:
[]
内に取り得るパターンの文字を入れる。[ab]
は'a'
または'b'
というパターンを表している - 文字列のパターン:
()
内に取り得るパターンの文字列を入れて|
で繋げる。(abc|def)
は"abc"
または"def"
というパターンを表している -
regex_match
:指定した文字列が、basic_regex
オブジェクト(正規表現オブジェクト)のパターンと一致しているかの真偽値を返す
#include <string>
#include <regex>
int main() {
string s1 = "aAa9";
std::string s2 = "bBb2";
std::string s2 = "cCc1";
// basic_regexオブジェクトの定義
regex re("(aAa|cCc)[1-5]");
if (regex_match(s1, re)) { ~ } // false
if (regex_match(s2, re)) { ~ } // false
if (regex_match(s3, re)) { ~ } // true
}
例題1
ABC277B - Playing Cards Validation
#include <bits/stdc++.h>
using namespace std;
bool solve() {
int N; cin >> N;
regex re("[HDCS][ATJQK2-9]");
set<string> st;
for (int i = 0; i < N; ++i) {
string S; cin >> S;
if (st.count(S)) return false;
if (!regex_match(S, re)) return false;
st.insert(S);
}
return true;
}
int main() {
if (solve()) cout << "Yes" << endl;
else cout << "No" << endl;
}
例題2
#include <bits/stdc++.h>
using namespace std;
int main() {
string S;
cin >> S;
regex re("(dream|dreamer|erase|eraser)*");
if (regex_match(S, re)) cout << "YES" << endl;
else cout << "NO" << endl;
}
間違いのご指摘や補足などがあれば、コメントいただけると幸いです。