Unclosed Character Class Error?

前端 未结 5 1561
难免孤独
难免孤独 2020-12-10 01:59

Here is the error:

Exception in thread \"main\" java.util.regex.PatternSyntaxException: Unclosed character class near index 3
], [
   ^
    at java.util.rege         


        
相关标签:
5条回答
  • 2020-12-10 02:31

    Split receives a regex and [, ] characters have meaning in regex, so you should escape them with \\[ and \\].

    The way you are currently doing it, the parser finds a ] without a preceding [ so it throws that error.

    0 讨论(0)
  • 2020-12-10 02:31
      .split("], [")
                 ^---start of char class
                      end----?
    

    Change it to

    .split("], \[")
               ^---escape the [
    
    0 讨论(0)
  • 2020-12-10 02:32

    TL;DR

    You want:

    .split("\\], \\[")`
    

    Escape each square bracket twice — once for each context in which you need to strip them from their special meaning: within a Regular Expression first, and within a Java String secondly.

    Consider using Pattern#quote when you need your entire pattern to be interpreted literally.


    Explanation

    String#split works with a Regular Expression but [ and ] are not standard characters, regex-wise: they have a special meaning in that context.

    In order to strip them from their special meaning and simply match actual square brackets, they need to be escaped, which is done by preceding each with a backslash — that is, using \[ and \].

    However, in a Java String, \ is not a standard character either, and needs to be escaped as well.

    Thus, just to split on [, the String used is "\\[" and you are trying to obtain:

    .split("\\], \\[")
    

    A sensible alternative

    However, in this case, you're not just semantically escaping a few specific characters in a Regular Expression, but actually wishing that your entire pattern be interpreted literally: there's a method to do just that

    0 讨论(0)
  • 2020-12-10 02:39

    String.split() takes a regular expression, not a normal string as an argument. In a regular expression, ] and [ are special characters, which need to be preceded by backslashes to be taken literally. Use .split("\\], \\["). (the double backslashes tell Java to interpret the string as "\], \[").

    0 讨论(0)
  • 2020-12-10 02:48

    Try to use it

     String stringToSplit = "8579.0,753.34,796.94,\"[784.2389999999999,784.34]\",\"[-4.335912230999999, -4.3603307895,4.0407909059, 4.08669583455]\",[],[],[],0.1744,14.4,3.5527136788e-15,0.330667850653,0.225286999939,Near_Crash";
     String [] arraySplitted = stringToSplit.replaceAll("\"","").replaceAll("\\[","").replaceAll("\\]","").trim().split(",");
    
    0 讨论(0)
提交回复
热议问题