GROUPS & ALTERNATION

Replacing with groups

In a replacement string, `$1` and `$2` insert what each group captured.

In a replacement string, `$1` inserts what group 1 captured and $& the whole match. Note the sigil flips: inside the pattern a backreference is \1, but in the replacement string it is $1. Swap "Doe, Jane" into "Jane Doe": pattern (\w+), (\w+), replacement $2 $1.

This lesson switches the playground to replace mode: pattern on the left, replacement on the right. Replacement strings are plain text apart from the $ references.

More replacement tokens: $& is the whole match, $<name> a named group, and $$ a literal dollar sign. MDN: specifying a string as the replacement.

PRACTICE - 3 DRILLS 0/3 DONE
DRILL 1/3

Turn "Last, First" into "First Last" on every line.

s/
->
Doe, Jane
must become:
Jane Doe
Smith, John
Lee, Sam
must become:
John Smith
Sam Lee
DRILL 2/3- Reformat dates

Rewrite ISO dates (YYYY-MM-DD) as DD/MM/YYYY.

s/
->
2026-06-15
must become:
15/06/2026
from 2025-01-02
to 2025-12-31
must become:
from 02/01/2025
to 31/12/2025
DRILL 3/3- Config lines

Rewrite each "key: value" config line as "value=key".

s/
->
host: localhost
must become:
localhost=host
port: 8080
mode: debug
must become:
8080=port
debug=mode