メインコンテンツにスキップ
eLearner.app
モジュール 4 · レッスン 4 / 4コース内の 16/32~12 min
モジュールのレッスン (4/4)

名前付きグループと後方参照

When the number of groups grows, remembering that $2 is "the month" and $5 is "the year" becomes fragile. The (?<name>...) syntax lets you name a group: you access it by name via groups.name (and in replacements as $<name>).

Code
Pattern: (?<anno>\d{4})-(?<mese>\d{2})-(?<giorno>\d{2})
Sample:  2024-03-15
Gruppi:
  anno    = "2024"
  mese    = "03"
  giorno  = "15"

The editor shows the named groups next to the match.

Backreference

A backreference lets you refer, inside the same pattern, to a previous capture. The syntax:

  • \1, \2, … -- numbered reference (to group 1, 2, …).
  • \k<name> -- named reference.
Code
Pattern: \b(\w+)\s+\1\b
Sample:  un test un test il il gatto
                                ^^^^^

It matches consecutive duplicate words: (\w+) captures a word, then \s+\1 requires a space and the same word.

Self-documenting code and named back-references

Named groups improve the readability of JavaScript code: instead of referring to match[1], you access match.groups.name. Inside the pattern itself, referencing them is done with the \\k<name> syntax.

Try it

運動#regex.m4.l4.e1
試行回数: 0読み込み中…

Find every date in YYYY-MM-DD format naming the groups `anno`, `mese`, `giorno`.

エディターを読み込み中…
ヒントを表示

Syntax: (?<name>pattern). The match shows the groups under the 'named' entry.

3 回の試行後に解決策が利用可能になります

Review exercise

運動#regex.m4.l4.e2
試行回数: 0読み込み中…

Find consecutive duplicate words (e.g. `il il`, `casa casa`). Use a group for the first one and a backreference `\\1` for the second.

エディターを読み込み中…
ヒントを表示

\\b(\\w+)\\s+\\1\\b: the first word is (\\w+), then a space, then the SAME word \\1.

3 回の試行後に解決策が利用可能になります

Additional challenge

運動#regex.m4.l4.e3
試行回数: 0読み込み中…

Find HTML/XML tag pairs (e.g. `<b>text</b>` or `<i>text</i>`) ensuring that the closing tag matches the opening tag using a named backreference.

エディターを読み込み中…
ヒントを表示

Assign the name (?<tag>\w+) and close it with \k<tag>.

3 回の試行後に解決策が利用可能になります