Groovy:为什么我需要加倍转义方括号? [英] Groovy: Why do I need to double escape square brackets?

查看:556
本文介绍了Groovy:为什么我需要加倍转义方括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不起作用?

"hello[world".split("\[")

并且这样做:

and this does:

"hello[world".split("\\[")


推荐答案

这实际上是两个在不同上下文中的转义,因为参数是一个表示为字符串的正则表达式。

This is actually two escapes in different contexts, due to the fact that the argument is a regular expression represented as a string.

[必须被转义,否则它在正则表达式中会有特殊含义。正则表达式的转义会使它 \ [。但是, \ 必须被转义,因为它在字符串中有特殊含义(用于转义和用数字值表示字符)。

The [ has to be escaped because otherwise it would have a special meaning in the regular expression. The escape for the regular expression would make it \[. But then the \ has to be escaped as it has special meaning in a string (for escaping and for representing characters by numeric value).

可能会更糟糕,因为 \ 字符用于在上下文中转义。如果要按 \ 字符进行拆分,则必须将其转义( \\ )正则表达式的用法,但是你有两个 \ 字符,这两个字符必须在字符串上下文中转义。如果你把它写成一个常量,那么在你正在分割的原始字符串中的用法也需要转义,所以类似的分割将如下所示:

It can be much worse, as the \ character is used for escaping in both contexts. If you want to split by the \ character, you have to escape it (\\) for the regular expression usage, but then you have two \ characters, which both have to be escaped in string context. The usage in the original string you are splitting would also need the escape if you're writing it as a constant, so the analogous split would look like:

"hello\\world".split("\\\\")

这篇关于Groovy:为什么我需要加倍转义方括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆