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
std::regex
works with std::string
(narrow characters).std::wregex
works with std::wstring
(wide characters).std::regex
for standard ASCII or UTF-8 strings.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.
An introduction to regular expressions, and how to use them in C++ with the standard library's regex
, regex_match
, and regex_search