std::regex vs std::wregex
What is the difference between std::regex and std::wregex?
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 foundstd::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 foundKey Differences
std::regexworks withstd::string(narrow characters).std::wregexworks withstd::wstring(wide characters).- Use
std::regexfor standard ASCII or UTF-8 strings. - Use
std::wregexfor 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.
Regular Expressions
An introduction to regular expressions, and how to use them in C++ with std::regex, std::regex_match, and std::regex_search