C++: Validate a whole identifier with regex_match
An identifier check should reject extra characters at either end. std::regex_match requires the entire input to match, so a valid-looking substring cannot make a longer invalid value pass.
Prepare a scratch directory
Tested on Linux with GCC 14.2.0 in C++20 mode. You need Bash, a C++20 compiler and standard library, a text editor, and the mktemp, rm, and rmdir utilities. Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save as cpp-regex-match-whole-identifier.cpp:
#include <cassert>
#include <iostream>
#include <regex>
#include <string>
int main() {
const std::regex pattern{R"(([A-Z]{2})-([0-9]{3}))"};
const std::string valid = "AB-123";
std::smatch match;
if (!std::regex_match(valid, match, pattern)) return 1;
std::cout << "prefix: " << match[1].str() << '\n';
std::cout << "digits: " << match[2].str() << '\n';
for (const std::string input : {"xAB-123", "AB-123x", "AB-12", ""}) {
assert(!std::regex_match(input, pattern));
}
std::cout << "invalid cases rejected: 4\n";
}Compile and run:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic cpp-regex-match-whole-identifier.cpp -o cpp-regex-match-whole-identifier &&
./cpp-regex-match-whole-identifierObserved output:
prefix: AB
digits: 123
invalid cases rejected: 4How it works
The first capture contains two uppercase ASCII letters and the second contains three ASCII digits. Captures are read only after success. A raw string literal keeps the pattern readable. The default grammar is ECMAScript, and the named pattern is compiled once before the checks.
Limits and choices
The captured digit text still needs numeric parsing if arithmetic is required. Match results retain iterators into the original string, so keep that string alive and unchanged while using them. Standard regex offers no general resource budget. Keep patterns fixed and inputs bounded when handling hostile input.
The C++ working draft specifies the library operation used here. The example uses the C++20 interface tested above; newer draft additions are outside its scope.
Clean up
rm -- cpp-regex-match-whole-identifier.cpp cpp-regex-match-whole-identifier
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect the remaining files before removing anything else.
Acknowledgements
This post was created with assistance from AI.