Java 相当于 Python repr()?

发布于 2024-08-02 20:08:59 字数 207 浏览 5 评论 0 原文

有没有一种 Java 方法可以像 Python 的 repr 一样工作?例如,假设函数名为 repr,

"foo\n\tbar".repr()

则返回的结果

"foo\n\tbar"

不会

foo
        bar

像 toString 那样。

Is there a Java method that works like Python's repr? For example, assuming the function were named repr,

"foo\n\tbar".repr()

would return

"foo\n\tbar"

not

foo
        bar

as toString does.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

悲凉≈ 2024-08-09 20:09:00

Java 没有 repr 函数,但是 repr 已经让你满意了(完全公开:我是 repr 的作者)。

Java has no repr-Function, but repr has got you covered (Full disclosure: I am the author of repr).

祁梦 2024-08-09 20:09:00

使用静态方法 escapeJava来自 StringEscapeUtilsApache Commons 文本

String repr = "\"" + StringEscapeUtils.escapeJava(myString) + "\"";

Use the static method escapeJava from the StringEscapeUtils class in Apache Commons Text.

String repr = "\"" + StringEscapeUtils.escapeJava(myString) + "\"";
谁对谁错谁最难过 2024-08-09 20:09:00

这可以做到,但是有点黑客,它使用 StringUtilsreplaceEach 实现简单的替换:

String hello = "hello\n\tworld\n\n\t";       
        String replaced = StringUtils.replaceEach(hello, new String[] {"\n", "\t", "\r", "\f"}, 
                                                         new String[] {"\\n", "\\t", "\\r", "\\f"});
        System.out.println("Replaced " + replaced);

This will do it, but it's a bit of a hack, it uses StringUtils and replaceEach from Common Lang to achieve a simple replace:

String hello = "hello\n\tworld\n\n\t";       
        String replaced = StringUtils.replaceEach(hello, new String[] {"\n", "\t", "\r", "\f"}, 
                                                         new String[] {"\\n", "\\t", "\\r", "\\f"});
        System.out.println("Replaced " + replaced);
你穿错了嫁妆 2024-08-09 20:09:00

不认为有特定的方法——但这将在没有 commons lang 的情况下解决它:

public class test {

public test() throws Exception {
    byte[] hello = "hello\n\tworld\n\n\t".getBytes();
    System.out.println(new String(hexToByte(stringToHex(hello).replaceAll("0a", "5c6e")
                                                              .replaceAll("09", "5c74"))));
}

public static void main(String[] args) throws Exception {
    new test();
}

public static String stringToHex(byte[] b) throws Exception {
    String result = "";
    for (int i = 0; i < b.length; i++) {
        result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    return result;
}

public static byte[] hexToByte(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
    }
    return data;
}

}

don't think there's a specific method -- but this'll solve it without commons lang:

public class test {

public test() throws Exception {
    byte[] hello = "hello\n\tworld\n\n\t".getBytes();
    System.out.println(new String(hexToByte(stringToHex(hello).replaceAll("0a", "5c6e")
                                                              .replaceAll("09", "5c74"))));
}

public static void main(String[] args) throws Exception {
    new test();
}

public static String stringToHex(byte[] b) throws Exception {
    String result = "";
    for (int i = 0; i < b.length; i++) {
        result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    return result;
}

public static byte[] hexToByte(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
    }
    return data;
}

}

压抑⊿情绪 2024-08-09 20:09:00

Jython 似乎已经做到了这一点。理论上,您可以包含 Jython jar,启动解释器,然后在相关对象上实际运行 repr(object)。可能比您想要的更多开销,但完全符合您的描述。

如果您想在应用程序中嵌入 Jython 解释器,请考虑 http://wiki.python.org /jython/JythonFaq/EmbeddingJython

It appears that Jython already does this. You could, in theory, include the Jython jar, startup an interpreter, and actually run repr(object) on the object in question. Probably more overhead than you want, but does exactly what you describe.

If you want to embed the Jython interpreter in your application, consider http://wiki.python.org/jython/JythonFaq/EmbeddingJython .

星星的軌跡 2024-08-09 20:09:00

如果您使用 Groovy,它提供了类似的 StringEscapeUtils 作为 Apache Commons Lang:

StringEscapeUtils.escapeJava("foo\n\tbar")

In case you are using Groovy, it provides a similar StringEscapeUtils class as Apache Commons Lang:

StringEscapeUtils.escapeJava("foo\n\tbar")
℉絮湮 2024-08-09 20:09:00

如果您只想在字符串上使用它,那么在紧要关头,您可以编写一个方法来遍历字符串并用转义码替换特殊字符(无论您想要什么“特殊”定义)。这就是我会做的。 (我进行了快速搜索,但 Google 上没有任何结果,因此编写方法可能比寻找现有的实现更快)

If you're only going to be using this on strings, in a pinch you could just write a method that goes through the string and replaces special characters (for whatever definition of "special" you want) with their escape codes. That's what I would do. (I did a quick search and nothing came up on Google, so it might be faster to just write the method than to hunt for an existing implementation)

大海や 2024-08-09 20:09:00

如果有这样的方法,那么用 Java 编写 quines 就会变得非常容易,因为它可以解决转义引号的问题。鉴于Java中最简单的quines都需要手动插入引号字符及其字符代码,因此不太可能存在这种方法。

If there were such a method, it would make writing quines in Java really easy, because it would solve the problem of escaping the quotes. Seeing as the simplest quines in Java all require manually inserting the quote character manually with its character code, it is unlikely that such a method exists.

最舍不得你 2024-08-09 20:08:59

在某些项目中,我使用以下辅助函数来完成类似于 Python 的字符串 repr 的操作:

private static final char CONTROL_LIMIT = ' ';
private static final char PRINTABLE_LIMIT = '\u007e';
private static final char[] HEX_DIGITS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

public static String toPrintableRepresentation(String source) {

    if( source == null ) return null;
    else {

        final StringBuilder sb = new StringBuilder();
        final int limit = source.length();
        char[] hexbuf = null;

        int pointer = 0;

        sb.append('"');

        while( pointer < limit ) {

            int ch = source.charAt(pointer++);

            switch( ch ) {

            case '\0': sb.append("\\0"); break;
            case '\t': sb.append("\\t"); break;
            case '\n': sb.append("\\n"); break;
            case '\r': sb.append("\\r"); break;
            case '\"': sb.append("\\\""); break;
            case '\\': sb.append("\\\\"); break;

            default:
                if( CONTROL_LIMIT <= ch && ch <= PRINTABLE_LIMIT ) sb.append((char)ch);
                else {

                    sb.append("\\u");

                    if( hexbuf == null ) 
                        hexbuf = new char[4];

                    for( int offs = 4; offs > 0; ) {

                        hexbuf[--offs] = HEX_DIGITS[ch & 0xf];
                        ch >>>= 4; 
                    }

                    sb.append(hexbuf, 0, 4);
                }
            }
        }

        return sb.append('"').toString();
    }
}

与此处给出的许多其他解决方案相比,它的主要优点是,它不会仅过滤一组有限的字符串。不可打印的字符(如那些基于替换的解决方案),但只是所有不可打印的 ASCII 字符。其中一些本来可以写得更好一点,但它实际上完成了它的工作...

注意,像 Python 函数一样,这个函数将用引号将字符串括起来。如果您不希望这样,则必须消除 while 循环之前和之后的 append('"') 调用。

In some projects, I use the following helper function to accomplish something akin to Python's repr for strings:

private static final char CONTROL_LIMIT = ' ';
private static final char PRINTABLE_LIMIT = '\u007e';
private static final char[] HEX_DIGITS = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

public static String toPrintableRepresentation(String source) {

    if( source == null ) return null;
    else {

        final StringBuilder sb = new StringBuilder();
        final int limit = source.length();
        char[] hexbuf = null;

        int pointer = 0;

        sb.append('"');

        while( pointer < limit ) {

            int ch = source.charAt(pointer++);

            switch( ch ) {

            case '\0': sb.append("\\0"); break;
            case '\t': sb.append("\\t"); break;
            case '\n': sb.append("\\n"); break;
            case '\r': sb.append("\\r"); break;
            case '\"': sb.append("\\\""); break;
            case '\\': sb.append("\\\\"); break;

            default:
                if( CONTROL_LIMIT <= ch && ch <= PRINTABLE_LIMIT ) sb.append((char)ch);
                else {

                    sb.append("\\u");

                    if( hexbuf == null ) 
                        hexbuf = new char[4];

                    for( int offs = 4; offs > 0; ) {

                        hexbuf[--offs] = HEX_DIGITS[ch & 0xf];
                        ch >>>= 4; 
                    }

                    sb.append(hexbuf, 0, 4);
                }
            }
        }

        return sb.append('"').toString();
    }
}

Its main advantage over many of the other solutions given here is, that it does not filter only a limited set of non-printable characters (like those replace-based solutions), but simply all non-printable ASCII characters. Some of it could have been written slightly nicer, but it actually does its job...

Note, that like the Python function, this one will surround the string with quotes. If you do not want that, you will have to eliminate the append('"') calls before and after the while loop.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文