Validate email address using Regex in C++

Qucik one. Something I want to write down before I forget. Validating email addresses have been a constant pain for software developers. The RFC spec for a valid email is complex. No, it's not simply ^\S+@\S+\.\S+$. For example. The spec prohibits email addresses on TLD. Thus bob@example is not valid. There's a very helpful post on the internet that shares how to validate on using regex.

There's some discussion to have as there's edge cases that are not covered. But it's good enough. One problem. The site does not share how to do this in C++. That's what this post is about.

C++'s standard regex library by default runs in ECMAScript mode. But with different syntax of creating regex. Some quick adoption yields the following code

static const std::regex email_regex(R"(^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$)");
std::smatch match;
if(!std::regex_match(email, match, email_regex)) {
	// invalid email

You have it! Happy coding!

Okay, C++'s regex library is known to be slow. Replace it with Boost's and done.

Author's profile. Photo taken in VRChat by my friend Tast+
Martin Chang
Systems software, HPC, GPGPU and AI. I mostly write stupid C++ code. Sometimes does AI research. Chronic VRChat addict

I run TLGS, a major search engine on Gemini. Used by Buran by default.

  • marty1885 \at
  • Matrix:
  • Jami: a72b62ac04a958ca57739247aa1ed4fe0d11d2df