Library contents

C++ std::regex_error

Constructing a regex from an invalid pattern throws regex_error.

A simple example

std::regex_error

  1. Start with Pattern consisting of one open bracket
  2. Do this Compile the pattern
  3. Result Invalid pattern
The bracket begins a character class that never closes. Compiling detects the problem before a search.

Syntax

C++ syntax
std::regex(rule)
Run these examples in C++

Save one example at a time as lesson.cpp. Use C++17 and a Unix-style shell.

c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson

Validate a saved product search

A store lets staff save a regular expression for product labels. A buyer leaves an opening bracket unfinished, so the search editor should highlight the invalid rule before it is saved.

ResultFix the search pattern
lesson.cpp
#include <iostream>
#include <regex>

int main() {
    try {
        std::regex rule("[sale");
    } catch (const std::regex_error&) {
        std::cout << "Fix the search pattern\n";
    }
    return 0;
}
Output
Fix the search pattern

The bracket opens a character class that never closes. The editor asks the buyer to fix it.

Advertisements

Save a costume search

A costume librarian groups two rack prefixes in a character class. Compile the pattern before saving the search. An incomplete character class must go back to the editor.

Given[AB]
Worked resultPattern accepted

Catch a broken shelf filter

A clerk forgets the closing bracket in a saved shelf search. Compile the pattern before saving the search. An incomplete character class must go back to the editor.

Given[AB
Worked resultEdit pattern

What to watch for

Validate the user-supplied rule when saving it. Other components can then reuse a compiled expression.

Documentation for std::regex_error