0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【AtCoder】正規表現の使い方

Last updated at Posted at 2024-07-24

ポイント

  • 文字のパターン:[]内に取り得るパターンの文字を入れる。[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

ABC049C - 白昼夢

#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;
}

間違いのご指摘や補足などがあれば、コメントいただけると幸いです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?