How to detect ANSI color in linux ?
#include <regex>
#include <string>
int main(){
std::string str = "\033[34m Hello \033[30m World";
std::smatch match;
std::regex blue_pattern(R"(\033\[34m)");
if(std::regex_search(str,match,blue_pattern)){
std::cout << str << std::endl;
}
return 0;
}
Of course the If condition is not valid.
Can someone explain me why ?
How to detect ANSI color in linux ?
#include <regex>
#include <string>
int main(){
std::string str = "\033[34m Hello \033[30m World";
std::smatch match;
std::regex blue_pattern(R"(\033\[34m)");
if(std::regex_search(str,match,blue_pattern)){
std::cout << str << std::endl;
}
return 0;
}
Of course the If condition is not valid.
Can someone explain me why ?
Share Improve this question edited Mar 17 at 6:34 Ulrich Eckhardt 17.5k5 gold badges31 silver badges60 bronze badges asked Mar 16 at 19:29 Ninja-Flex6969Ninja-Flex6969 1701 gold badge1 silver badge8 bronze badges 6 | Show 1 more comment1 Answer
Reset to default 3If you just want to find a substring in a string, please refer to Check if a string contains a string in C++.
Regarding the regex issue you have, you can match the ESC character using \x1B
, or \u001B
.
As per the C++ regex documentation,
The following character escape sequences are recognized:
CharacterEscape ::
ControlEscape
c ControlLetter
HexEscapeSequence
UnicodeEscapeSequence
IdentityEscape
As you see, there is no octal notation support. More:
The decimal escape
\0
is NOT a backreference: it is a character escape that represents theNUL
character. It cannot be followed by a decimal digit.
So, inside your code, you may use
std::regex blue_pattern(R"(\x1B\[34m)");
and the
#include <regex>
#include <string>
#include <iostream>
int main(){
std::string str = "\033[34m Hello \033[30m World";
std::smatch match;
std::regex blue_pattern(R"(\x1B\[34m)");
if(std::regex_search(str,match,blue_pattern)){
std::cout << "Found" << std::endl;
}
return 0;
}
code will print Found
. See the online demo.
\033
is a single character in a regular string literal but 4 characters in a raw string literal. – n. m. could be an AI Commented Mar 16 at 19:34\xXX
notation,std::regex blue_pattern(R"(\x1B\[34m)");
– Wiktor Stribiżew Commented Mar 16 at 19:46std::regex blue_pattern("\033" R"(\[34m)");
would be an option. – Ted Lyngmo Commented Mar 17 at 15:00