Groovy: Why do I need to double the escape square brackets?

Why is this not working?

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

and it does:

"hello[world".split("\\[")
+5
source share
2 answers

These are actually two escape files in different contexts due to the fact that the argument is a regular expression represented as a string.

[must be escaped, because otherwise it will have special meaning in regular expression. The output for regular expression will make it \[. But then it \must be escaped, since it has a special meaning in the string (for escaping and for representing characters by a numerical value).

, \ . \, (\\) , \, . , , , , :

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

Groovy .

Groovy 1.1-BETA-1

assert "hello[world".split("\\[") == ["hello", "world"]

, OK, Groovy 1.0 .

assert "hello[world".split(/\[/) == ["hello", "world"]

, 1.1-BETA-1, Groovy 1.0-jsr-01 1.0 , Groovy 1.0-beta-10 .

"hello[world".split("\\[").each{println it}

Groovy 1.0--5 -3,

hello
world

1.0-beta-4 print

[.]
[.]
hello
world
+1