1
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?

More than 1 year has passed since last update.

正規表現

1
Last updated at Posted at 2025-09-02

/\(グループ(\d+)\)/

/ ... /
JavaScriptで正規表現を表す記法

\(
( は正規表現の中で「特別な意味(グループ化)」を持つ文字です。
そのまま「文字としての ( 」を探したいときは ( と書いてエスケープします。
👉 ここでは「テキスト中の ((かっこ)」を探している。

(\d+)
(...) → 「キャプチャグループ」。括弧内にマッチした部分を後で取り出せる。
\d → 数字(0〜9)。
+ → 直前のパターンが 1回以上 繰り返される。
👉 つまり「1文字以上の数字」にマッチして、それを取り出す。

\)
) も正規表現の中では特別な意味を持つので ) と書いてエスケープ。
👉 「文字としての )」を探している。

まとめると
/\(グループ(\d+)\)/ は
「(グループ に続いて1文字以上の数字があり、最後に ) がついている部分」
にマッチする。

title.js
const text = "あ(グループ1)";
const match = text.match(/\(グループ(\d+)\)/);

console.log(match[0]); // "(グループ1)" ← 全体にマッチした部分
console.log(match[1]); // "1" ← 丸括弧の中 (\d+) の部分だけ
title.js
const apiResponse = { a: "あ(グループ1),い(グループ2),う(グループ1)" };

// カンマで分割
const values = apiResponse.a.split(",");

// 正規表現でグループ番号を取り出してクラスを付与
const spans = values.map(v => {
  const match = v.match(/\(グループ(\d+)\)/);
  if (match) {
    const groupNum = match[1];       // "1" or "2" etc
    const cls = `class-0${groupNum}`;
    return `<span class="${cls}">${v}</span>`;  // v は "あ(グループ1)" そのまま
  } else {
    // グループ指定がなければ class なし
    return `<span>${v}</span>`;
  }
});

// HTML文字列に結合
const html = spans.join("");

// DOMに挿入(例: #result に表示)
document.getElementById("result").innerHTML = html;
title.js
const apiResponse = { a: "あ(かえで),い(もみじ),う(葉っぱ),え(もみじ)" };

// 日本語 → ローマ字の変換表
const romanizeMap = {
  "かえで": "kaede",
  "もみじ": "momiji",
  "葉っぱ": "happa"
};

// カンマで分割
const values = apiResponse.a.split(",");

// ()の中をキャプチャしてクラスに
const spans = values.map(v => {
  const match = v.match(/\(([^)]+)\)/);
  if (match) {
    const jpName = match[1];                // 日本語のグループ名
    const groupName = romanizeMap[jpName] || "unknown"; // 対応表で変換
    return `<span class="class-${groupName}">${v}</span>`;
  } else {
    return `<span>${v}</span>`;
  }
});

// 出力用HTML
const html = spans.join("");
document.getElementById("result").innerHTML = html;
1
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
1
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?