StringEscapeUtils 不转义 {

发布于 12-19 09:02 字数 291 浏览 1 评论 0原文

我有以下字符串:

String str = "{% assign foo = values %}.{{ foo[0] }}."

我正在尝试将其编译为模式:

Pattern p = Pattern.compile(StringEscapeUtils.escapeJava(str));

但编译失败并出现“非法重复”错误,我猜测这是由于 '{' 字符没有被转义。

怎样才能正确逃脱呢?最好不要在每个字符前面添加“\\”。

I have the following string:

String str = "{% assign foo = values %}.{{ foo[0] }}."

And I'm trying to compile it as a pattern with:

Pattern p = Pattern.compile(StringEscapeUtils.escapeJava(str));

but the compilation fails with the "Illegal repetition" error which I'm guessing is due to the '{' char not being escaped.

How can I escape it properly? Preferably without adding "\\" in front of every character.

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

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

发布评论

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

评论(3

沒落の蓅哖2024-12-26 09:02:04

您不需要 StringEscapeUtils.escapeJava() 您需要 Pattern.quote()

You do not want StringEscapeUtils.escapeJava() You want Pattern.quote().

溺孤伤于心2024-12-26 09:02:04

使用 \ 转义,在 Java 字符串中,您还必须转义 \ 本身:

String str = "\\{% assign foo = values %\\}.\\{\\{ foo\\[0\\] \\}\\}\\.";

要自动转义元字符,您可以使用 Pattern.quote(str)

Escape with a \, in Java strings you have to escape the \ it self as well:

String str = "\\{% assign foo = values %\\}.\\{\\{ foo\\[0\\] \\}\\}\\.";

To escape meta characters automatically you can use Pattern.quote(str).

清君侧2024-12-26 09:02:04

大多数 PCRE 引擎,您可以用 \Q ... \E 包围正则表达式中的文字文本,

其中 \Q 是元字符的起始引用,\E 是引用元字符的结束。

它本质上是用 '\\$1'< 全局查找/替换 '([.*+?|()\[\]{}^\$\\])' 。 /code> 位于 \Q 和 \E 之间。

Most PCRE engines, you can surround the literal text within the regex with \Q ... \E

where \Q is start qote of metachars, \E is end of quote metachars.

It essentially does a global find/replace of '([.*+?|()\[\]{}^\$\\])' with '\\$1' between the \Q and \E.

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