Regular Expressions

std::regex vs std::wregex

What is the difference between std::regex and std::wregex?

Abstract art representing computer programming

In C++, std::regex and std::wregex are both used for working with regular expressions, but they serve different purposes depending on the type of strings you are working with.

std::regex

std::regex is used with std::string, which means it is designed to work with narrow-character strings (i.e., single-byte character strings).

This is the most common use case for regular expressions in C++ when dealing with standard ASCII or UTF-8 encoded text.

Example with std::regex:

#include <iostream>
#include <regex>

int main() {
  std::string text{"Hello world"};
  std::regex pattern{"world"};

  if (std::regex_search(text, pattern)) {
    std::cout << "Match found";
  } else {
    std::cout << "No match";
  }
}
Match found

std::wregex

std::wregex is used with std::wstring, which means it is designed to work with wide-character strings (i.e., multi-byte character strings).

This is useful when working with Unicode text that requires more than one byte per character, such as text in languages like Chinese, Japanese, or Korean.

Example with std::wregex:

#include <iostream>
#include <regex>

int main() {
  std::wstring text{L"Hello world"};
  std::wregex pattern{L"world"};

  if (std::regex_search(text, pattern)) {
    std::wcout << L"Match found";
  } else {
    std::wcout << L"No match";
  }
}
Match found

Key Differences

  • std::regex works with std::string (narrow characters).
  • std::wregex works with std::wstring (wide characters).
  • Use std::regex for standard ASCII or UTF-8 strings.
  • Use std::wregex for Unicode strings that require wide characters.

Understanding when to use std::regex versus std::wregex depends on the type of text you are processing.

For most applications involving standard English text or UTF-8 encoded text, std::regex is sufficient.

However, for applications that need to handle Unicode text with wide characters, std::wregex is the appropriate choice.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved