Mastering Regular Expressions in Playwright Assertions

When, Why, and How to Use RegEx Without Making Tests Fragile

Mastering Regular Expressions in Playwright Assertions

1. Do We Always Have to Use Regular Expressions in Playwright?

Short answer: ❌ No.

Playwright supports both:

  • Exact string matching
  • Regular Expression (RegEx) matching

You should choose based on stability, not habit.

// Exact match
await expect(page).toHaveTitle('Inspection Manager');

// RegEx match
await expect(page).toHaveTitle(/Inspection Manager/);

2. Why RegEx Is So Common in Playwright (Industry Reality)

In real applications:

  • Titles include environment names (Staging, UAT, Prod)
  • Text includes dynamic values (IDs, names, dates)
  • UI text may change slightly but meaning stays the same

✅ RegEx helps prevent flaky tests

Example:

Inspection Manager | Staging
Inspection Manager | Production
await expect(page).toHaveTitle(/Inspection Manager/);

✔ Stable across environments
✔ Less maintenance
✔ Cleaner CI runs

3. Most Common RegEx Patterns Used in Playwright

3.1 Partial Match (Most Used)

await expect(page).toHaveTitle(/Inspection Manager/);

✔ Checks if the text exists anywhere

3.2 Exact Match Using RegEx

await expect(page).toHaveTitle(/^Inspection Manager$/);

✔ Use when the title must not change

3.3 Case-Insensitive Match

await expect(page).toHaveTitle(/inspection manager/i);

i → Ignore case
✔ Useful when UI text casing is inconsistent

3.4 Dynamic Text Handling

await expect(page.locator('.toast'))
.toHaveText(/Inspection saved successfully/);

Handles:

Inspection saved successfully at 10:45 AM

3.5 Matching Numbers or IDs

await expect(page.locator('.inspection-id'))
.toHaveText(/Inspection ID: d+/);

d+ → One or more digits

4. Where RegEx Is Commonly Used in Playwright

Example:

await expect(page).toHaveURL(//inspection/d+/);

5. When You SHOULD NOT Use RegEx ❌

Avoid RegEx when:

  • Text is static
  • UI copy is contractually fixed
  • You want strict validation

Bad practice:

await expect(button).toHaveText(/Save/);

Better:

await expect(button).toHaveText('Save');

✔ Detects accidental UI changes
✔ Stronger test intent

6. RegEx vs String — Decision Guide

7. Best Practices (Senior QA Level)

✅ Prefer simple RegEx
❌ Avoid complex patterns unless needed

✅ Comment why RegEx is used

// Title contains env-specific suffix
await expect(page).toHaveTitle(/Inspection Manager/);

❌ Don’t mask bugs with overly-loose patterns

// BAD
await expect(page).toHaveTitle(/.*/);

8. Final Rule of Thumb

Use RegEx to handle variability, not to hide problems.

A good Playwright test:

  • Is stable
  • Is readable
  • Fails for the right reason

Social Media: LinkedIn, Twitter, Instagram, YouTube, GitHub.


Mastering Regular Expressions in Playwright Assertions was originally published in Javarevisited on Medium, where people are continuing the conversation by highlighting and responding to this story.

This post first appeared on Read More