String TranslateEscapes Unescaping

Turn escape sequences that exist as characters into their real control characters with translateEscapes, without regex or manual replacement.

JavaConfig Management

Code

javasnippet
18 lines
public class EscapeUnwinder {

    public static void main(String[] args) {
        // 配置文件里读到的是字面上的反斜杠序列,不是真实的制表/换行
        String raw = "col1\\tcol2\\nline2\\q";

        // translateEscapes 只翻译合法序列:\t \n 等变真实控制字符
        String translated = raw.translateEscapes();
        System.out.println("lines: " + translated.lines().count());
        System.out.println("first line: " + translated.lines().findFirst().orElse(""));

        // 非法序列保留原样:\\q 不是 Java 转义,不抛异常
        System.out.println("raw tail kept: " + translated.endsWith("\\q"));

        // 对照:手动 replace 需要为每种序列写一条,且容易漏
        System.out.println("chars: " + translated.chars().distinct().count());
    }
}

How it works

String TranslateEscapes Unescaping keeps everything in the class EscapeUnwinder and the function main.

Applying it

Running the file prints labeled results such as lines:, first line:, raw tail kept: — each operation’s effect is visible in the output.

Statements that matter

String translated = raw.translateEscapes();
String raw = "col1\\tcol2\\nline2\\q";

Interactive Tools for This Topic

FAQ

What does String TranslateEscapes Unescaping print when run?
Execute the whole file; each printed line is prefixed with a label like `lines:`, `first line:`, `raw tail kept:`.