简体   繁体   中英

Scala Pattern Syntax Exception

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.

转义{

val string = "{one}{two}".split("}\\{")

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})

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM