I'm trying to split a string in by the characters "}{"
. However I am getting an error:
> val string = "{one}{two}".split("}{")
java.util.regex.PatternSyntaxException: Illegal repetition near index 0
}{
^
I am not trying to use regex or anything. I tried using "\}\{"
and it also doesn't work.
Well... the reason is that split
treats its parameter string as a regular expression.
Now, both {
and }
are special character in regular expressions.
So you will have to skip the special characters of regex world for split
's argument, like this,
val string = "{one}{two}".split("\\}\\{")
// string: Array[String] = Array({one, two})
Escape the {
val string = "{one}{two}".split("}\\{")
There are two ways to force a metacharacter to be treated as an ordinary character:
-> precede the metacharacter with a backslash.
String[] ss1 = "{one}{two}".split("[}\\{]+");
System.out.println(Arrays.toString(ss1));
output:
[one, two]
-> enclose it within \Q (which starts the quote) and \E (which ends it).
When using this technique, the \Q and \E can be placed at any location within the expression, provided that the \Q comes first.
String[] ss2 = "{one}{two}".split("[}\\Q{\\E]+");
System.out.println(Arrays.toString(ss2));
output:
[one, two]