📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)

15行目: 15行目:
移行を検討する場合は、既存のQRegExpクラスを使用したコードにおいて、新しい機能の実装時やコードのメンテナンス時に徐々にQRegularExpressionクラスへ移行することが推奨される。<br>
移行を検討する場合は、既存のQRegExpクラスを使用したコードにおいて、新しい機能の実装時やコードのメンテナンス時に徐々にQRegularExpressionクラスへ移行することが推奨される。<br>
<br>
<br>
 
QRegularExpressionクラスで頻繁に使用するメソッドを以下に示す。<br>
* <code>hasMatch</code>メソッド
*: パターンがテキストにマッチしたかどうかをbool値で返す。
*: trueの場合はマッチが成功、falseの場合は失敗を意味する。
* <code>captured</code>メソッド
*: マッチした部分文字列や、括弧でグループ化された部分を取得する。
*: 引数無しの場合は完全なマッチを返す。
*: 数値を指定する場合、その番号のキャプチャグループを返す。
*: 文字列を指定する場合、その名前のキャプチャグループを返す。
<br>
<u>※注意</u><br>
* パターンの最適化
*: 頻繁に使用する正規表現パターンは、オブジェクトとして保持して再利用することにより、パフォーマンスを向上させることができる。
* エラー処理
*: isValidメソッドを使用して、正規表現パターンの妥当性を確認することが推奨される。
<br>
<syntaxhighlight lang="c++">
#include <QRegularExpression>
#include <QDebug>
class RegexExamples
{
public:
    // メールアドレスの検証
    static bool validateEmail(const QString& email)
    {
      // CaseInsensitiveOptionオプションは、大文字と小文字を区別せずにマッチングを行う
      QRegularExpression re("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$", QRegularExpression::CaseInsensitiveOption);
      QRegularExpressionMatch match = re.match(email);
      return match.hasMatch();
    }
    // 電話番号からハイフンを除去
    static QString normalizePhoneNumber(const QString& phone)
    {
      QRegularExpression re("[^0-9]");
      return phone.replace(re, "");
    }
    // HTMLタグの抽出
    static void extractHtmlTags(const QString& html)
    {
      QRegularExpression re("<([a-zA-Z0-9]+)[^>]*>");
      QRegularExpressionMatchIterator i = re.globalMatch(html);
      while (i.hasNext()) {
          QRegularExpressionMatch match = i.next();
          qDebug() << "Found tag:" << match.captured(1);
      }
    }
    // 日付形式の変換 (YYYY/MM/DD -> MM-DD-YYYY)
    static QString convertDateFormat(const QString& date)
    {
      QRegularExpression re("(\\d{4})/(\\d{2})/(\\d{2})");
      QRegularExpressionMatch match = re.match(date);
      if (match.hasMatch()) {
          return QString("%1-%2-%3").arg(match.captured(2))
                                    .arg(match.captured(3))
                                    .arg(match.captured(1));
      }
      return date;
    }
    // 文字列内の数値を抽出して合計を計算
    static int sumNumbersInText(const QString& text)
    {
      QRegularExpression re("\\d+");
      QRegularExpressionMatchIterator i = re.globalMatch(text);
      int sum = 0;
      while (i.hasNext()) {
          QRegularExpressionMatch match = i.next();
          sum += match.captured().toInt();
      }
      return sum;
    }
    // URLからクエリパラメータを抽出
    static QMap<QString, QString> parseQueryParameters(const QString& url)
    {
      QMap<QString, QString> params;
      QRegularExpression re("([^=&?]+)=([^&]*)");
      QRegularExpressionMatchIterator i = re.globalMatch(url);
      while (i.hasNext()) {
          QRegularExpressionMatch match = i.next();
          params[match.captured(1)] = match.captured(2);
      }
      return params;
    }
    // コードからコメントを抽出
    static void extractComments(const QString& code)
    {
      // 単一行コメント
      // MultilineOptionオプションは、複数行のテキストで、行ごとに独立してパターンマッチングを行う
      // ^ (行頭) と $ (行末) が各行に対して機能する
      QRegularExpression singleLine("//(.*)$", QRegularExpression::MultilineOption);
      // 複数行コメント
      QRegularExpression multiLine("/\\*([^*]|\\*(?!/))*\\*/");
      auto processMatch = [](const QRegularExpressionMatch& match) {
          QString comment = match.captured(0).trimmed();
          qDebug() << "Found comment:" << comment;
      };
      // globalMatchメソッドを使用して、テキスト内の全てのマッチを処理
      QRegularExpressionMatchIterator i1 = singleLine.globalMatch(code);
      while (i1.hasNext()) {
          processMatch(i1.next());
      }
      QRegularExpressionMatchIterator i2 = multiLine.globalMatch(code);
      while (i2.hasNext()) {
          processMatch(i2.next());
      }
    }
};
</syntaxhighlight>
<br>
<syntaxhighlight lang="c++">
// 使用例
#include <QDebug>
qDebug() << "Email validation: " << RegexExamples::validateEmail("test@example.com");
qDebug() << "Normalized phone: " << RegexExamples::normalizePhoneNumber("123-456-7890");
QString html = "<div>content</div><p>paragraph</p>";
RegexExamples::extractHtmlTags(html);
qDebug() << "Converted date: " << RegexExamples::convertDateFormat("2024/03/25");
QString text = "Values: 10, 20, 30";
qDebug() << "Sum of numbers: " << RegexExamples::sumNumbersInText(text);
QString url = "https://example.com?name=John&age=25";
QMap<QString, QString> params = RegexExamples::parseQueryParameters(url);
qDebug() << "URL parameters:" << params;
QString code = "// This is a comment\nint x = 5;\n/* Multi\nline\ncomment */";
RegexExamples::extractComments(code);
</syntaxhighlight>
<br><br>
<br><br>