Scala Pattern Syntax Exception

后端 未结 3 1904
遥遥无期
遥遥无期 2021-01-27 09:55

I\'m trying to split a string in by the characters \"}{\". However I am getting an error:

> val string = \"{one}{two}\".split(\"}{\")
java.util.r         


        
相关标签:
3条回答
  • 2021-01-27 10:18

    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]
    
    0 讨论(0)
  • 2021-01-27 10:23

    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})
    
    0 讨论(0)
  • 2021-01-27 10:27

    Escape the {

    val string = "{one}{two}".split("}\\{")
    
    0 讨论(0)
提交回复
热议问题