← Runnable Projects

阅读中文版本

Regex Tester CLI

A Node CLI that tests a regular expression against input text or stdin, printing every match with its index and capture groups.

intermediatejavascriptunverified

Project

node-regex-tester-cli

Entry point: regex.mjs

Install

node --version

Run

node regex.mjs "\w+@\w+" "a@b c@d"

Test

node --test regex.test.mjs

Expected output

Prints each match with its character index and any capture groups, or reports no matches.

Dependencies

  • node >=20

What it does

Compiles the pattern with the global flag and iterates matches, guarding against zero-length matches that would otherwise loop forever. Each match reports its index, span, and capture groups.

const [pattern, ...rest] = process.argv.slice(2);
const text = rest.join(' ') || '';
if (!pattern) { console.error('usage: regex <pattern> <text>'); process.exit(1); }

let re;
try { re = new RegExp(pattern, 'g'); } catch (e) { console.error('invalid regex: ' + e.message); process.exit(1); }

let m; let count = 0;
while ((m = re.exec(text)) !== null) {
  const start = m.index; const end = start + m[0].length;
  console.log('match ' + start + '..' + end + ': ' + m[0] + (m.length > 1 ? ' groups=[' + m.slice(1).join(',') + ']' : ''));
  count++;
  if (m.index === re.lastIndex) re.lastIndex++;
}
if (count === 0) console.log('no matches');

Run and verify

node regex.mjs "\w+@\w+" "a@b c@d"

Run the test command to check the implementation: node --test regex.test.mjs.

Expected Output

Matching an email-like pattern against a@b c@d yields two matches on one line each:

match 0..3: a@b
match 4..7: c@d

Limitations

Uses JavaScript regex semantics, which lack some features other engines have and include catastrophic-backtracking pitfalls; a pathological pattern from stdin can stall the process.