这是一个极简的例子:
it("actual length") {
import scala.io.AnsiColor
val str = AnsiColor.RED + "c" + AnsiColor.RESET
assert(str.length == 1)
}但在执行此测试时,它显示str的长度为10,而显示长度应为1(所有ANSI转义字符都应具有0长度)。
怎么改正呢?
发布于 2022-09-02 20:33:30
length方法的doc说这实际上计算了Unicode码单元的数量
在Java文档中,Unicode代码点用于U+0000和U+10FFFF之间的字符值,Unicode代码单元用于16位字符值,这些值是UTF-16编码的代码单元。
/**
* Returns the length of this string.
* The length is equal to the number of Unicode code units in the string.
*
* Returns the length of the sequence of characters represented by this object.
*/
public int length() {
return value.length >> coder();
}没有内置的解决方案来计算您想要的内容,但是您可以使用regex简单地删除它们。AnsiColor转义码似乎有一个精确的模式:\u001b + [ + 1-2 digits + m
val str: String = AnsiColor.RED + "c" + AnsiColor.RESET
println(str.replaceAll("\\u001B\\[\\d{1,2}m", "").length) // 1https://stackoverflow.com/questions/73586626
复制相似问题