Home > OS >  Function to check if a string is an ANSI escape sequence?
Function to check if a string is an ANSI escape sequence?

Time:07-20

I need a C function (or object) able to tell me if a certain string is an ANSI escape sequence.

So, if I have for example:

std::string ansi = "\033[0m";

I would need something like this:

is_escape_char( ansi )

which returns false or true if the string is an ANSI escape sequence. Is it possible?

CodePudding user response:

If you know it's at the start of the string

bool is_escape_char(std::string_view str)
{
   return str.starts_with("\033");
}

Otherwise look for it anywhere in the string

bool is_escape_char(std::string_view str)
{
   return std::string_view::npos != str.find("\033");
}

Depending on what you need, you can capture the index in the return of 'find', determine which sequence it is, and find the next code that finishes the sequence. But it requires inspection of the characters following the initial escape.

CodePudding user response:

Take a look at regular expressions in C .

The regex for an any ansii escape sequence is: \033\[((?:\d|;)*)([a-zA-Z])

  • Related