ANSI color escape sequence chars appearing inside String.length();

979 Views Asked by At

When coloring a String with an ANSI escape sequence, then taking the .length() of the String in question, it does not give the length of the visible part of the String, instead including part of the escape sequence.

import java.util.*;

public class ColorTest {
    public static void main(String[] args){
        String RED    = "\u001B[31m";
        String test = "Test";

        // Prints length with color
        System.out.println(test);
        System.out.println("Length: "+test.length());
        
        // Prints length with color
        test = RED+test;
        System.out.println(test);
        System.out.println("Length: "+test.length());

        // Prints every char found in the String
        char[] testCharList = test.toCharArray();
        for(char x : testCharList){
            System.out.print(x+" ");
        }
        System.out.println(" ");

    }
}

output: output

Due to the many different colors having different amounts of digits in their escape sequences, (Red being 31, and a bright red background being 101) a total subtraction of a set number from the String.length() number is not feasible. I am seeking a universal solution to this issue that will work for all colors, and combinations of them, where it only shows the displayed String's length.

1

There are 1 best solutions below

2
EricChen1248 On

This isn't a very optimal way, but it should work if regex performance isn't a very big issue.

public static int getStringLengthWithoutANSI(String str) {
    return str.replaceAll("(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]", "").length();
}