How to make control characters visible?

2020-04-11 10:17发布

I have to display string with visible control characters like \n, \t etc. I have tried quotations like here, also I have tried to do something like

Pattern pattern = Pattern.compile("\\p{Cntrl}");
Matcher matcher = pattern.matcher(str);
String controlChar = matcher.group();
String replace = "\\" + controlChar;
result = result.replace(controlChar, replace);

but I have failed

3条回答
地球回转人心会变
2楼-- · 2020-04-11 10:24

just doing

result = result.replace("\\", "\\\\");

will work!!

查看更多
叛逆
3楼-- · 2020-04-11 10:36

Alternative: Use visible characters instead of escape sequences.

To make control characters "visible", use the characters from the Unicode Control Pictures Block, i.e. map \u0000-\u001F to \u2400-\u241F, and \u007F to \u2421.

Note that this requires output to be Unicode, e.g. UTF-8, not a single-byte code page like ISO-8859-1.

private static String showControlChars(String input) {
    StringBuffer buf = new StringBuffer();
    Matcher m = Pattern.compile("[\u0000-\u001F\u007F]").matcher(input);
    while (m.find()) {
        char c = m.group().charAt(0);
        m.appendReplacement(buf, Character.toString(c == '\u007F' ? '\u2421' : (char) (c + 0x2400)));
        if (c == '\n') // Let's preserve newlines
            buf.append(System.lineSeparator());
    }
    return m.appendTail(buf).toString();
}

Output using method above as input text:

␉private static String showControlChars(String input) {␍␊
␉␉StringBuffer buf = new StringBuffer();␍␊
␉␉Matcher m = Pattern.compile("[\u0000-\u001F\u007F]").matcher(input);␍␊
␉␉while (m.find()) {␍␊
␉␉␉char c = m.group().charAt(0);␍␊
␉␉␉m.appendReplacement(buf, Character.toString(c == '\u007F' ? '\u2421' : (char) (c + 0x2400)));␍␊
␉␉␉if (c == '\n')␍␊
␉␉␉␉buf.append(System.lineSeparator());␍␊
␉␉}␍␊
␉␉return m.appendTail(buf).toString();␍␊
␉}␍␊
查看更多
疯言疯语
4楼-- · 2020-04-11 10:41

Simply replace occurences of '\n' with the escaped version (i.e. '\\n'), like this:

final String result = str.replace("\n", "\\n");

For example:

public static void main(final String args[]) {
    final String str = "line1\nline2";
    System.out.println(str);
    final String result = str.replace("\n", "\\n");
    System.out.println(result);
}

Will yield the output:

line1
newline
line1\nnewline
查看更多
登录 后发表回答