Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 38 ยท Projects and Practice

Regex Practice Challenges

Sharpen your regular expression skills with twelve graded challenges covering anchors, classes, groups, backreferences, lookaround and replacement. Edit the patterns, run the tests, then compare with the solutions.

Reading about regex teaches vocabulary. Writing patterns teaches fluency. This page gives you twelve challenges, each with a list of strings that must match and strings that must not. A tiny test harness runs your pattern against both lists and prints PASS or FAIL with the examples that went wrong.

How to use it: in the first editor, replace each placeholder pattern (the empty /^$/) with your own, run, and keep going until everything passes. Resist looking at the solutions until you have tried. The second editor holds one possible solution for each challenge, with notes. There are often several correct answers; if yours passes the tests and is not ambiguous, it is fine.

The challenges

  1. ZIP codes. Five digits, optionally followed by a hyphen and four more digits.
  2. Repeated words. Find a word that is immediately repeated, like "the the".
  3. 12-hour time. 1:05 pm, 12:59 AM; hours 1 to 12, minutes 00 to 59, am or pm in any case.
  4. IPv4 address. Four numbers from 0 to 255 separated by dots, with no leading zeros.
  5. Thousands separators. 1,234, 12,345,678: groups of exactly three digits after the first group of one to three.
  6. Five-letter palindromes. Lowercase words like level or civic.
  7. Domain from a URL. Capture the host of an http or https URL, without port or path.
  8. Quoted strings. A double-quoted string that may contain escaped quotes like \".
  9. Words without vowels in a line. Match whole words that contain no a e i o u (letters only).
  10. Hex color or rgb(). Either #abc / #aabbcc or rgb( three numbers ).
  11. No consecutive duplicates. Whole strings of letters that do not contain the same letter twice in a row.
  12. Reformat with replace. Turn Lastname, Firstname into Firstname Lastname (one replace call).
Node.js Challenge board: write your patterns here

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Hints

Open these one at a time only if you are stuck.

  1. Anchor both ends and make the hyphen part optional with a group: (?:...)?.
  2. Capture a word with (\w+) and refer to it again with \1. A \b before and after keeps it from matching inside longer words.
  3. The hour is either 1 to 9 or 10, 11, 12: write it as an alternation.
  4. One octet is 25[0-5], 2[0-4]\d, 1\d\d, [1-9]?\d. Repeat octet\. three times, then one more octet.
  5. First group: \d{1,3}. Then any number of ,\d{3}.
  6. A five-letter palindrome has the shape abcba: capture the first two letters and reuse them backwards.
  7. After the scheme and //, the host is characters that are not /, : or ?, but must not be empty.
  8. Inside quotes, each piece is either a character that is not a quote or backslash, or a backslash followed by any character.
  9. Use a negated class [^aeiou\W\d_], or a lookahead that forbids vowels: ^(?![a-z]*[aeiou])[a-z]+$ with the i flag if needed.
  10. Alternation of two anchored forms, with and for hex digits.
  11. A negative lookahead that looks for (.)\1 at any position.
  12. Two groups separated by , and the replacement $2 $1.

Solutions

Node.js One solution for each challenge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notes on the solutions

  • Challenge 4 shows building a long pattern from a reusable piece. The order of alternatives in an octet matters: longer forms like 25[0-5] come before [1-9]?\d, otherwise 255 would match only as 25. Anchors then force the whole octet.
  • Challenge 6 uses backreferences to describe a symmetric word, something a plain character class cannot do.
  • Challenge 9 uses a lookahead to say "no vowel anywhere" before matching the letters; it is read as: at the start, assert that you cannot find a vowel after any run of letters.
  • Challenge 11 is a negative lookahead with a backreference: (?!.*(.)\1) means "nowhere in the string is there a character followed by itself".
  • Challenge 2 deliberately uses \b on both sides. Without the closing \b, "this his" would be flagged because \1 could match his partially inside a longer word.
  • Good patterns are not only correct but bounded and unambiguous. Re-read validating input and hardening for the habits that keep them safe.

Going further

Make up your own challenges from data you work with: log files, CSV exports, copied text. For each pattern write at least three strings that should match and three that should not, including edge cases like an empty string, extra whitespace and non-ASCII letters. The test list is as valuable as the pattern. When you want more, revisit the earlier projects and extend them: the log analyzer, the Markdown converter and the template engine.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should every pattern come with both matching and non-matching examples?

    Matching examples catch patterns that are too strict, and non-matching examples catch patterns that are too permissive.
  2. 2. In the IPv4 octet, why is 25[0-5] listed before [1-9]?\d?

    If the short form came first, 255 could be matched as 25 and the anchor or next dot would then fail.
  3. 3. What does (?!.*(.)\1) assert?

    The negative lookahead fails if any position has a captured character followed by a backreference to it.
  4. 4. Which approach finds the word repeated in "it was was fun"?

    Capturing a word and referring to it with \1 describes immediate repetition of any word.

Summary

  • Practice with tests: for each pattern keep strings that must match and strings that must not.
  • Backreferences describe repetition and symmetry; lookaheads express "must" and "must not" conditions.
  • Order alternatives from most specific to least specific and anchor whole-string patterns.
  • Reuse pieces to build long patterns, and keep them bounded and unambiguous.
  • Keep a collection of your own challenges from real data.

Back to the track: Regular Expressions