Quinton Marchi
Quinton Marchi

Reputation: 53

Invalid Escape Character

Making a server in java, First off, Here's the code.

    AnsiConsole.out.println("This is a Test.");
    AnsiConsole.out.println("\e[0;31m Red");
    AnsiConsole.out.println("\e[0;34m Blue");
    AnsiConsole.out.println("\e[0;32m Green");
    AnsiConsole.out.println("\e[1;33m Yellow");

So, my issue is that it reads the escape characters as illegal. Any Comments?

Using the Jansi Library http://jansi.fusesource.org/index.html

Upvotes: 1

Views: 9005

Answers (4)

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

I'm assuming you're trying to produce ANSI Escape Sequences here.

\e is not a valid character in Java, what you need is instead \u001b which is the start of the ANSI sequence.

AnsiConsole.out.println("\u001b[0;31m Red");

Upvotes: 2

Razvan
Razvan

Reputation: 10103

If you want to include a '\' (backslash) in the printed string you should escape it with another '\' => AnsiConsole.out.println("\\e[0;31m Red");

Currently java understands you try to escape 'e' which is not a special character and it complains about that.

Upvotes: 0

assylias
assylias

Reputation: 328855

It's because \e is not a valid escape sequence. If you do want to print the backslash, you need to escape it: "\\e[0;31m Red"

You can check this page for a list of valid escape sequences.

Upvotes: 1

Adam
Adam

Reputation: 15803

You need to escape the backslash:

AnsiConsole.out.println("This is a Test.");
AnsiConsole.out.println("\\e[0;31m Red");
AnsiConsole.out.println("\\e[0;34m Blue");
AnsiConsole.out.println("\\e[0;32m Green");
AnsiConsole.out.println("\\e[1;33m Yellow");

Because in Java, the backslash \ has a special meaning in strings: it's used for special characters such as \n (new line) or \t (tab).

There's a good description of the topic here.

Upvotes: 2

Related Questions