Unclosed Character Class Error?

2020-01-29 08:37发布

Here is the error:

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character class near index 3
], [
   ^
    at java.util.regex.Pattern.error(Pattern.java:1924)
    at java.util.regex.Pattern.clazz(Pattern.java:2493)
    at java.util.regex.Pattern.sequence(Pattern.java:2030)
    at java.util.regex.Pattern.expr(Pattern.java:1964)
    at java.util.regex.Pattern.compile(Pattern.java:1665)
    at java.util.regex.Pattern.<init>(Pattern.java:1337)
    at java.util.regex.Pattern.compile(Pattern.java:1022)
    at java.lang.String.split(String.java:2313)
    at java.lang.String.split(String.java:2355)
    at testJunior2013.J2.main(J2.java:31)

This is the area of the code that is causing the issues.

String[][] split = new String[1][rows];

split[0] = (Arrays.deepToString(array2d)).split("], ["); //split at the end of an array row

What does this error mean and what needs to be done to fix the code above?

标签: java regex split
5条回答
Emotional °昔
2楼-- · 2020-01-29 09:03

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.

查看更多
甜甜的少女心
3楼-- · 2020-01-29 09:05
  .split("], [")
             ^---start of char class
                  end----?

Change it to

.split("], \[")
           ^---escape the [
查看更多
唯我独甜
4楼-- · 2020-01-29 09:19

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 "\], \[").

查看更多
forever°为你锁心
5楼-- · 2020-01-29 09:19

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(",");
查看更多
家丑人穷心不美
6楼-- · 2020-01-29 09:21

String#split works with a Regular Expression but [ (and ]) are not standard characters, "regex-wise". So, they need to be escaped — 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 Java String used is "\\["; and you are trying to obtain:

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

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

查看更多
登录 后发表回答