Regular expressions match text patterns. They help validate test data, filter logs and make assertions flexible without accepting too much.
On this cheat sheet
Building blocks
. | Any character except line terminators by default. |
\d / \D | Digit / not a digit. |
\w / \W | Word character / not one. |
\s / \S | Whitespace / not whitespace. |
[A-Z] | One character in a range. |
[^0-9] | One character outside a set. |
*, +, ? | Zero or more, one or more, zero or one. |
{2,5} | Between two and five repeats. |
^ / $ | Start / end of input. |
(cat|dog) | Group and alternatives. |
\. | Literal dot. |
Common patterns
| Data | Practical pattern |
|---|---|
| Positive integer | ^[1-9]\d*$ |
| Signed decimal | ^-?\d+(\.\d+)?$ |
| UUID | ^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ |
| ISO date shape | ^\d{4}-\d{2}-\d{2}$ |
| Simple email shape | ^[^\s@]+@[^\s@]+\.[^\s@]+$ |
| HTTP(S) URL shape | ^https?:\/\/[^\s]+$ |
| Only whitespace | ^\s*$ |
| Leading or trailing whitespace | ^\s|\s$ |
| Order ID | ^ORD-\d{6}$ |
Shape is not validity:
2026-99-99 matches the ISO date shape. Parse the value to validate a real date. Use a URL parser or verification flow for URLs and emails.JavaScript and Playwright examples
expect('ORD-123456').toMatch(/^ORD-\d{6}$/);
await expect(page.getByTestId('reference'))
.toHaveText(/^REF-[A-Z0-9]{8}$/);
const clean = value.replace(/^\s+|\s+$/g, '');
Useful flags: i ignores case, g finds all matches, m changes line anchors and u enables Unicode-aware behaviour.
Testing tips
- Anchor with
^and$when the whole value must match. - Escape special characters when they should be literal.
- Test empty, near-match, Unicode and very long input.
- Avoid overly broad
.*assertions. - Keep complex patterns commented and covered by tests.
- Do not use regex alone as a security boundary.