gpt4 book ai didi

java - Guava 是否提供了对字符串进行转义的方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:17:26 28 4
gpt4 key购买 nike

我需要转义 String 中的特殊字符。

Guava 提供了 Escaper类,它正是这样做的:

Escaper escaper = Escapers.builder()
.addEscape('[', "\\[")
.addEscape(']', "\\]")
.build();

String escapedStr = escaper.escape("This is a [test]");

System.out.println(escapedStr);
// -> prints "This is a \[test\]"

现在我有一个转义的 String,我需要取消转义它,但我在 Guava 中找不到任何东西来执行此操作。

我期待 Escaper 有一个 unescape() 方法,但事实并非如此。

编辑:我知道取消转义可能很棘手,在某些无意义的情况下甚至是不可能的。

例如,这种 Escaper 用法可能会导致歧义:

Escaper escaper = Escapers.builder()
.addEscape('@', " at ")
.addEscape('.', " dot ")
.build();

除非转义的数据仅包含电子邮件地址而仅此而已,否则您无法通过取消转义来安全地取回数据。

安全使用 Escaper 的一个很好的例子是 HTML 实体:

Escaper escaper = Escapers.builder()
.addEscape('&', "&")
.addEscape('<', "&lt;")
.addEscape('>', "&gt;")
.build();

在这里,您可以安全地转义任何文本,将其合并到 HTML 页面中,并随时取消转义以显示它,因为您涵盖了所有可能的歧义。

总而言之,我不明白为什么 unescaping 如此有争议。我认为开发人员有责任正确使用此类,了解他的数据并避免歧义。根据定义,转义意味着您最终将需要转义。否则,它是混淆或其他一些概念。

最佳答案

不,它没有。显然,这是故意的。引自 this discussion Chris Povirk 回答说:

The use case for unescaping is less clear to me. It's generally not possible to even identify the escaped source text without a parser that understands the language. For example, if I have the following input:

String s = "foo\n\"bar\"\n\\";

Then my parser has to already understand \n, \", and \\ in order to identify that...

foo\n\"bar\"\n\\

...is the text to be "unescaped." In other words, it has to do the unescaping already. The situation is similar with HTML and other formats: We don't need an unescaper so much as we need a parser.

所以看起来你必须自己做。

关于java - Guava 是否提供了对字符串进行转义的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34091304/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com