Case-Sensitive Regex
How do I make a regex pattern case-sensitive or case-insensitive in C++?
In C++, you can control the case sensitivity of your regex patterns by using flags with the std::regex
constructor. Here's how you can make your regex patterns case-sensitive or case-insensitive.
Case-Sensitive Regex
By default, regex patterns in C++ are case-sensitive. This means that the pattern hello
will not match the string Hello
. For example:
#include <iostream>
#include <regex>
int main() {
std::string text{"Hello world"};
std::regex pattern{"hello"}; // Case-sensitive
if (std::regex_search(text, pattern)) {
std::cout << "Match found";
} else {
std::cout << "No match";
}
}
No match
Case-Insensitive Regex
To make a regex pattern case-insensitive, you can pass the flag std::regex::icase
to the std::regex
constructor. This flag tells the regex engine to ignore case when matching the pattern. For example:
#include <iostream>
#include <regex>
int main() {
std::string text{"Hello world"};
std::regex pattern{
"hello",
std::regex::icase // Case-insensitive
};
if (std::regex_search(text, pattern)) {
std::cout << "Match found";
} else {
std::cout << "No match";
}
}
Match found
Using Regex Flags
You can use the std::regex::icase
flag to make your entire pattern case-insensitive. However, C++ does not support inline flags (like some other languages do) within the pattern itself, so the flag must be applied to the entire pattern.
Practical Use: Case-Insensitive Search
If you want to find all occurrences of a word in a text regardless of the case, you can use std::regex_search
with the icase
flag.
#include <iostream>
#include <regex>
int main() {
std::string text{
"The quick brown fox jumps over the lazy dog. "
"The Quick Brown Fox Jumps Over The Lazy Dog."
};
std::regex pattern{"the", std::regex::icase};
auto words_begin = std::sregex_iterator(
text.begin(), text.end(), pattern
);
auto words_end = std::sregex_iterator();
for (
std::sregex_iterator i = words_begin;
i != words_end;
++i
) {
std::smatch match = *i;
std::cout << "Match: " << match.str() << "\n";
}
}
Match: The
Match: the
Match: The
Match: The
By using std::regex::icase
, you can make your regex patterns case-insensitive, allowing for more flexible and user-friendly text processing.
Regular Expressions
An introduction to regular expressions, and how to use them in C++ with std::regex
, std::regex_match
, and std::regex_search