最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How detect ANSI color in linux with std::regex in C++ - Stack Overflow

programmeradmin2浏览0评论

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
  • 6 \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
  • 2 Use \xXX notation, std::regex blue_pattern(R"(\x1B\[34m)"); – Wiktor Stribiżew Commented Mar 16 at 19:46
  • The cpp regex docs do not say octal notation is supported, so I understand it is not supported. – Wiktor Stribiżew Commented Mar 16 at 19:53
  • Thank you @WiktorStribiżew Perfect explanation – Ninja-Flex6969 Commented Mar 16 at 21:05
  • 1 std::regex blue_pattern("\033" R"(\[34m)"); would be an option. – Ted Lyngmo Commented Mar 17 at 15:00
 |  Show 1 more comment

1 Answer 1

Reset to default 3

If 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 the NUL 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.

发布评论

评论列表(0)

  1. 暂无评论