Regular Expressions: JavaScript Dialect Introduction
Literal patterns, boundaries, captures, explicit conversion, global state, Unicode properties and safe literal replacement data. Regexes already appearing in Shell, awk, sed and JSON Schema are supporting uses; this module makes one dialect and its result contract explicit. No PCRE/POSIX portability or complete regex-family mastery.
Audience: Learners who can read a short script and save plain text.
Practice: 60 to 90 minutes.
Website reference edition
This introductory material is available here for reading and practice planning. New offline workbench exports, PDF and ZIP editions for these additions are not published. The released Atlas 0.11 downloads cover the earlier 19 packs only. These pages do not run teaching code or contact an AI service.
Runtime and boundaries
Run each fixed .cjs example with the installed /usr/local/bin/node --max-old-space-size=64. JavaScript is the host used to exercise one regular-expression dialect, not another newly counted identity. Examples use authored strings of at most 4096 characters and a five-second owned-process deadline in the test harness. These bounds and simple patterns are not a general defense for hostile patterns or arbitrary text. No RegExp.escape, arbitrary pattern construction, network or browser execution is used. Other regex engines and operating systems are untested.
Introductory module · 2 exercises
Lessons
Name the dialect and the matching question
A pattern can search for a substring or describe a whole input. The first example deliberately rejects extra prefixes, suffixes and a final newline. Specify flags along with the pattern; do not transplant syntax from another engine without checking it.
Keep the two layers of escaping visible
A regex literal and a JavaScript string passed to RegExp are different source forms. The filename example makes a literal dot explicit in both. All patterns here are authored constants; a constructor is not permission to turn arbitrary user text into pattern syntax.
Matching does not finish validation
Named captures can label parts of a match, but captured digits are still text. The record example converts minutes and enforces a small numeric range separately. Predict the difference between a malformed record and an otherwise matched value outside that range.
Repeated tests may carry state
A global regex object remembers lastIndex. The state example performs exactly three calls on one fixed string and shows the cursor after each call. For independent validation, avoid g/y or create/reset the intended state explicitly. No open-ended matching loop is taught here.
Unicode and replacement data need explicit rules
The letter exercise accepts a composed accented letter but rejects a combining mark by itself. Code points, UTF-16 units and grapheme clusters are different; no normalization is performed. The replacement exercise uses a callback so dollar sequences in replacement data remain literal.
Reference cards
Literal: /pattern/u
Fixed JavaScript regex with Unicode-aware mode.
Constructor: new RegExp("pattern", "u")
A string layer is parsed before the pattern layer.
Boundary: ^ ... $ without m
Use explicit full-input intent in these fixed patterns.
Alternatives: (?:read|code)
Group alternatives without adding a captured result.
Capture: (?<minutes>[0-9]{1,3})
Give captured text a useful name; convert and validate afterward.
State: g / lastIndex
Repeated calls can continue from a remembered cursor.
Unicode: \p{Letter} with u
Letter property is not a promise to accept every user-perceived name.
Replacement: replace(pattern, () => text)
Use the returned string as literal replacement text.
Support file: Regular Expressions JavaScript Dialect Introduction instructions.txt
Content-only candidate. Use only the fixed authored examples with their listed installed runtime. Run each fixed .cjs example with the installed /usr/local/bin/node --max-old-space-size=64. JavaScript is the host used to exercise one regular-expression dialect, not another newly counted identity. Examples use authored strings of at most 4096 characters and a five-second owned-process deadline in the test harness. These bounds and simple patterns are not a general defense for hostile patterns or arbitrary text. No RegExp.escape, arbitrary pattern construction, network or browser execution is used. Other regex engines and operating systems are untested. No browser/export/release acceptance is claimed.
Examples and practice
All code and values below are inert reading material. Preserve each exact filename and companion when making your own practice copy.
Regex 01 - Match a complete label
The alternation and one-to-two digit bound describe a small label contract. These ASCII digits are deliberate; an unrelated Unicode digit is not silently accepted.
Filename: Regex 01 Match a complete label.cjs
// Fixed authored fixtures; no user patterns, I/O or network.
function inspect(value) {
return /^(?:read|code)-[0-9]{1,2}$/u.test(value);
}
const cases = [{"name": "accepted", "input": "read-7", "expected": true}, {"name": "too many digits", "input": "read-123", "expected": false}, {"name": "extra prefix", "input": "xread-7", "expected": false}, {"name": "final newline", "input": "read-7\n", "expected": false}];
for (const item of cases) {
if (JSON.stringify(item.input).length > 4096) throw new Error("Fixture too large");
const actual = inspect(item.input);
if (JSON.stringify(actual) !== JSON.stringify(item.expected)) throw new Error("Unexpected result: " + item.name);
console.log(item.name + ": " + JSON.stringify(actual));
}
Expected output:
accepted: true too many digits: false extra prefix: false final newline: false
Recorded invocation:
/usr/local/bin/node --max-old-space-size=64 "Regex 01 Match a complete label.cjs"
Typed result contract
- variant
host-driver
- summary
accepted: true too many digits: false extra prefix: false final newline: false
- stdout
Type: string
"accepted: true\ntoo many digits: false\nextra prefix: false\nfinal newline: false\n"
- exit status
Type: integer
0
- stderr
- match
exact
- value
Authored case table
- variant
hosted-cases
- rows
- name
accepted
- input
Type: string
"read-7"
- expected value
Type: boolean
true
- name
too many digits
- input
Type: string
"read-123"
- expected value
Type: boolean
false
- name
extra prefix
- input
Type: string
"xread-7"
- expected value
Type: boolean
false
- name
final newline
- input
Type: string
"read-7\n"
- expected value
Type: boolean
false
Regex 02 - Escape a literal dot
The dot is escaped as a regex metacharacter. The constructor needs a second backslash for the JavaScript string; neither expression reads a file.
Filename: Regex 02 Escape a literal dot.cjs
// Fixed authored fixtures; no user patterns, I/O or network.
function inspect(value) {
return [/^read\.txt$/u.test(value), new RegExp("^read\\.txt$", "u").test(value)];
}
const cases = [{"name": "filename", "input": "read.txt", "expected": [true, true]}, {"name": "wildcard lookalike", "input": "readXtxt", "expected": [false, false]}, {"name": "prefix", "input": "xread.txt", "expected": [false, false]}, {"name": "newline", "input": "read.txt\n", "expected": [false, false]}];
for (const item of cases) {
if (JSON.stringify(item.input).length > 4096) throw new Error("Fixture too large");
const actual = inspect(item.input);
if (JSON.stringify(actual) !== JSON.stringify(item.expected)) throw new Error("Unexpected result: " + item.name);
console.log(item.name + ": " + JSON.stringify(actual));
}
Expected output:
filename: [true,true] wildcard lookalike: [false,false] prefix: [false,false] newline: [false,false]
Recorded invocation:
/usr/local/bin/node --max-old-space-size=64 "Regex 02 Escape a literal dot.cjs"
Typed result contract
- variant
host-driver
- summary
filename: [true,true] wildcard lookalike: [false,false] prefix: [false,false] newline: [false,false]
- stdout
Type: string
"filename: [true,true]\nwildcard lookalike: [false,false]\nprefix: [false,false]\nnewline: [false,false]\n"
- exit status
Type: integer
0
- stderr
- match
exact
- value
Authored case table
- variant
hosted-cases
- rows
- name
filename
- input
Type: string
"read.txt"
- expected value
Type: array
[ true, true ]
- name
wildcard lookalike
- input
Type: string
"readXtxt"
- expected value
Type: array
[ false, false ]
- name
prefix
- input
Type: string
"xread.txt"
- expected value
Type: array
[ false, false ]
- name
newline
- input
Type: string
"read.txt\n"
- expected value
Type: array
[ false, false ]
Regex 03 - Capture then validate
A successful pattern match supplies text captures. Numeric range checking is separate. The null result deliberately combines the two rejection paths in this tiny caller; production diagnostics may distinguish them.
Filename: Regex 03 Capture then validate.cjs
// Fixed authored fixtures; no user patterns, I/O or network.
function inspect(value) {
const match = /^(?<task>read|code):(?<minutes>[0-9]{1,3})$/u.exec(value);
if (!match) return null;
const minutes = Number(match.groups.minutes);
return minutes <= 120 ? {task: match.groups.task, minutes} : null;
}
const cases = [{"name": "record", "input": "read:20", "expected": {"task": "read", "minutes": 20}}, {"name": "zero", "input": "code:0", "expected": {"task": "code", "minutes": 0}}, {"name": "outside range", "input": "read:121", "expected": null}, {"name": "wrong separator", "input": "read=20", "expected": null}];
for (const item of cases) {
if (JSON.stringify(item.input).length > 4096) throw new Error("Fixture too large");
const actual = inspect(item.input);
if (JSON.stringify(actual) !== JSON.stringify(item.expected)) throw new Error("Unexpected result: " + item.name);
console.log(item.name + ": " + JSON.stringify(actual));
}
Expected output:
record: {"task":"read","minutes":20}
zero: {"task":"code","minutes":0}
outside range: null
wrong separator: nullRecorded invocation:
/usr/local/bin/node --max-old-space-size=64 "Regex 03 Capture then validate.cjs"
Typed result contract
- variant
host-driver
- summary
record: {"task":"read","minutes":20} zero: {"task":"code","minutes":0} outside range: null wrong separator: null- stdout
Type: string
"record: {\"task\":\"read\",\"minutes\":20}\nzero: {\"task\":\"code\",\"minutes\":0}\noutside range: null\nwrong separator: null\n"- exit status
Type: integer
0
- stderr
- match
exact
- value
Authored case table
- variant
hosted-cases
- rows
- name
record
- input
Type: string
"read:20"
- expected value
Type: object
{ "task": "read", "minutes": 20 }
- name
zero
- input
Type: string
"code:0"
- expected value
Type: object
{ "task": "code", "minutes": 0 }
- name
outside range
- input
Type: string
"read:121"
- expected value
Type: null
null
- name
wrong separator
- input
Type: string
"read=20"
- expected value
Type: null
null
Regex 04 - Observe global state
Three bounded calls expose the cursor state. A failed search resets it on this global regex, so reusing the object is not three independent yes/no checks.
Filename: Regex 04 Observe global state.cjs
// Fixed authored fixtures; no user patterns, I/O or network.
function inspect(value) {
const pattern = /a/gu;
const result = [];
for (let n = 0; n < 3; n += 1) result.push([pattern.test(value), pattern.lastIndex]);
return result;
}
const cases = [{"name": "two matches", "input": "aba", "expected": [[true, 1], [true, 3], [false, 0]]}, {"name": "one match cycles", "input": "a", "expected": [[true, 1], [false, 0], [true, 1]]}, {"name": "no match", "input": "", "expected": [[false, 0], [false, 0], [false, 0]]}];
for (const item of cases) {
if (JSON.stringify(item.input).length > 4096) throw new Error("Fixture too large");
const actual = inspect(item.input);
if (JSON.stringify(actual) !== JSON.stringify(item.expected)) throw new Error("Unexpected result: " + item.name);
console.log(item.name + ": " + JSON.stringify(actual));
}
Expected output:
two matches: [[true,1],[true,3],[false,0]] one match cycles: [[true,1],[false,0],[true,1]] no match: [[false,0],[false,0],[false,0]]
Recorded invocation:
/usr/local/bin/node --max-old-space-size=64 "Regex 04 Observe global state.cjs"
Typed result contract
- variant
host-driver
- summary
two matches: [[true,1],[true,3],[false,0]] one match cycles: [[true,1],[false,0],[true,1]] no match: [[false,0],[false,0],[false,0]]
- stdout
Type: string
"two matches: [[true,1],[true,3],[false,0]]\none match cycles: [[true,1],[false,0],[true,1]]\nno match: [[false,0],[false,0],[false,0]]\n"
- exit status
Type: integer
0
- stderr
- match
exact
- value
Authored case table
- variant
hosted-cases
- rows
- name
two matches
- input
Type: string
"aba"
- expected value
Type: array
[ [ true, 1 ], [ true, 3 ], [ false, 0 ] ]
- name
one match cycles
- input
Type: string
"a"
- expected value
Type: array
[ [ true, 1 ], [ false, 0 ], [ true, 1 ] ]
- name
no match
- input
Type: string
""
- expected value
Type: array
[ [ false, 0 ], [ false, 0 ], [ false, 0 ] ]
Regex 05 - Choose a Unicode policy
Solution: this narrow letter-only policy is intentional and not a universal personal-name validator. A combining mark is not in the Letter category, and no Unicode normalization occurs.
Filename: Regex 05 Choose a Unicode policy.cjs
// Fixed authored fixtures; no user patterns, I/O or network.
function inspect(value) {
return /^\p{Letter}+$/u.test(value);
}
const cases = [{"name": "composed accent", "input": "Élan", "expected": true}, {"name": "Han letters", "input": "漢字", "expected": true}, {"name": "decomposed accent", "input": "é", "expected": false}, {"name": "emoji", "input": "😀", "expected": false}];
for (const item of cases) {
if (JSON.stringify(item.input).length > 4096) throw new Error("Fixture too large");
const actual = inspect(item.input);
if (JSON.stringify(actual) !== JSON.stringify(item.expected)) throw new Error("Unexpected result: " + item.name);
console.log(item.name + ": " + JSON.stringify(actual));
}
Expected output:
composed accent: true Han letters: true decomposed accent: false emoji: false
Recorded invocation:
/usr/local/bin/node --max-old-space-size=64 "Regex 05 Choose a Unicode policy.cjs"
Typed result contract
- variant
host-driver
- summary
composed accent: true Han letters: true decomposed accent: false emoji: false
- stdout
Type: string
"composed accent: true\nHan letters: true\ndecomposed accent: false\nemoji: false\n"
- exit status
Type: integer
0
- stderr
- match
exact
- value
Authored case table
- variant
hosted-cases
- rows
- name
composed accent
- input
Type: string
"Élan"
- expected value
Type: boolean
true
- name
Han letters
- input
Type: string
"漢字"
- expected value
Type: boolean
true
- name
decomposed accent
- input
Type: string
"é"
- expected value
Type: boolean
false
- name
emoji
- input
Type: string
"😀"
- expected value
Type: boolean
false
Practice: Write a letter-only check and predict the composed accent, decomposed accent and emoji cases. Explain why rejecting one spelling does not make it invalid human text.
Regex 06 - Keep replacement data literal
Solution: the callback returns replacement data literally. A replacement string argument has special dollar substitutions; using a callback avoids that interpretation. The boundary rejects an overlong numeric token.
Filename: Regex 06 Keep replacement data literal.cjs
// Fixed authored fixtures; no user patterns, I/O or network.
function inspect(value) {
return value.text.replace(/\bid=[0-9]{1,3}\b/gu, () => value.replacement);
}
const cases = [{"name": "dollar data", "input": {"text": "id=7 id=9", "replacement": "$&"}, "expected": "$& $&"}, {"name": "no match", "input": {"text": "none", "replacement": "$1"}, "expected": "none"}, {"name": "simple replacement", "input": {"text": "id=12", "replacement": "done"}, "expected": "done"}, {"name": "overlong number", "input": {"text": "id=1234", "replacement": "done"}, "expected": "id=1234"}];
for (const item of cases) {
if (JSON.stringify(item.input).length > 4096) throw new Error("Fixture too large");
const actual = inspect(item.input);
if (JSON.stringify(actual) !== JSON.stringify(item.expected)) throw new Error("Unexpected result: " + item.name);
console.log(item.name + ": " + JSON.stringify(actual));
}
Expected output:
dollar data: "$& $&" no match: "none" simple replacement: "done" overlong number: "id=1234"
Recorded invocation:
/usr/local/bin/node --max-old-space-size=64 "Regex 06 Keep replacement data literal.cjs"
Typed result contract
- variant
host-driver
- summary
dollar data: "$& $&" no match: "none" simple replacement: "done" overlong number: "id=1234"
- stdout
Type: string
"dollar data: \"$& $&\"\nno match: \"none\"\nsimple replacement: \"done\"\noverlong number: \"id=1234\"\n"
- exit status
Type: integer
0
- stderr
- match
exact
- value
Authored case table
- variant
hosted-cases
- rows
- name
dollar data
- input
Type: object
{ "text": "id=7 id=9", "replacement": "$&" }- expected value
Type: string
"$& $&"
- name
no match
- input
Type: object
{ "text": "none", "replacement": "$1" }- expected value
Type: string
"none"
- name
simple replacement
- input
Type: object
{ "text": "id=12", "replacement": "done" }- expected value
Type: string
"done"
- name
overlong number
- input
Type: object
{ "text": "id=1234", "replacement": "done" }- expected value
Type: string
"id=1234"
Practice: Replace every bounded id token with supplied literal text, including the text $&. Predict whether id=1234 should be partially replaced.
Separate expected outcome: regex-invalid-pattern
- id
regex-invalid-pattern
- variant
expected-exception-driver
- category
Pattern construction failure, not a false match
- inputs
- code
Type: string
"try { new RegExp(\"(\", \"u\"); throw new Error(\"Unexpected success\"); } catch (error) { if (!(error instanceof SyntaxError)) throw error; console.log(error.name); }\n"
- stdout
Type: string
"SyntaxError\n"
- exit status
Type: integer
0
- stderr
- match
exact
- value
- execution meaning
Driver catches and verifies an expected exception; exit 0 is expected driver success, not parser acceptance.
- individual download control
false
Separate expected outcome: regex-duplicate-flags
- id
regex-duplicate-flags
- variant
expected-exception-driver
- category
Invalid flag construction, not matching
- inputs
- code
Type: string
"try { new RegExp(\"x\", \"ii\"); throw new Error(\"Unexpected success\"); } catch (error) { if (!(error instanceof SyntaxError)) throw error; console.log(error.name); }\n"
- stdout
Type: string
"SyntaxError\n"
- exit status
Type: integer
0
- stderr
- match
exact
- value
- execution meaning
Driver catches and verifies an expected exception; exit 0 is expected driver success, not parser acceptance.
- individual download control
false
Prompt templates
Planning text only; no AI service or export control is activated here.
Build an explicit contract
Create a small original example for the stated dialect with input assumptions and exact expected results. Language: {language}. Goal: {goal}. Runtime: {runtime}. Constraints: {constraints}.Debug the correct stage
Separate syntax or parsing failure from a nonmatch or application validation rejection; ask for the smallest authored reproducer. Language: {language}. Goal: {goal}. Runtime: {runtime}. Constraints: {constraints}.Test the boundary
Include empty, missing, unusual spelling and boundary cases; label expected rejections separately and do not claim execution without evidence. Language: {language}. Goal: {goal}. Runtime: {runtime}. Constraints: {constraints}.Preserve accepted inputs
Simplify the fixed pattern or configuration without changing accepted and rejected cases; keep data out of executable syntax. Language: {language}. Goal: {goal}. Runtime: {runtime}. Constraints: {constraints}.Explain the limits
State dialect, runtime, source date, intended input limits and untested features; this is introductory coverage rather than deep mastery. Language: {language}. Goal: {goal}. Runtime: {runtime}. Constraints: {constraints}.Historical measure scopes
These measures describe separate, overlapping source-example checks. They are not additive totals or website acceptance results.
- name
teaching_drivers
- count
6
- unit
teaching driver executions
- scope
Historical root module evidence; overlapping measures are not additive.
- tested on
2026-10-28
- runtime
Node.js 24.18.0 / V8 13.6.233.17-node.50; macOS 27.0.1 arm64
- name
embedded_case_assertions
- count
23
- unit
embedded case assertions
- scope
Historical root module evidence; overlapping measures are not additive.
- tested on
2026-10-28
- runtime
Node.js 24.18.0 / V8 13.6.233.17-node.50; macOS 27.0.1 arm64
- name
separate_expected_exception_drivers
- count
2
- unit
separate expected exception drivers
- scope
Historical root module evidence; overlapping measures are not additive.
- tested on
2026-10-28
- runtime
Node.js 24.18.0 / V8 13.6.233.17-node.50; macOS 27.0.1 arm64
Recorded test scope
- status
passed
- tested on
2026-10-28
- runtime
Node.js 24.18.0 / V8 13.6.233.17-node.50; macOS 27.0.1 arm64
- teaching drivers
6
- embedded case assertions
23
- separate expected exception drivers
2
- scope
Only fixed authored introductory examples; no browser/export or publication evidence.
These are dated source-example results, not website browser, export, PDF or cross-platform acceptance.
Further reading
- ECMAScript 2024 regular expression specification — Versioned normative reference; only exercised features are claimed.
- MDN JavaScript regular expression guide — Literals, constructors, matching methods and flags.
- MDN RegExp lastIndex — State in global and sticky regular expression objects.
- MDN Unicode character class escapes — Unicode property escapes and the boundary between characters and grapheme clusters.
- MDN String replace — Replacement callback versus replacement-string substitution syntax.
References are the reviewed source snapshot; they have not been rechecked at website publication time.