Java split function

Can someone help me in understanding how split in java works.I have the following code

 String temp_array[]; String rates = "RF\\0.6530\\0.6535\\D"; String temp = rates.substring(1, rates.length()); System.out.println(temp);// prints F\0.6530\0.6535\D String regex = "\\"; temp_array = temp.split(regex); String insertString = "INSERT into table values("+temp_array[0]+","+temp_array[1]+","+temp_array[2]+","+temp_array[3]+")"; 

however in split function i get the following exception

 Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \ ^ at java.util.regex.Pattern.error(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.util.regex.Pattern.<init>(Unknown Source) at java.util.regex.Pattern.compile(Unknown Source) at java.lang.String.split(Unknown Source) at java.lang.String.split(Unknown Source) at simple_hello.main(simple_hello.java:15) 
+8
java string arrays split regex
source share
6 answers

When you type "\\" this is actually one backslash (due to escaping special characters in Java strings).

Regular expressions also use a backslash as a special character, and you need to avoid it with another backslash. So at the end, you need to pass "\\\\" as a pattern according to one backslash.

+23
source share

\ is a special character in regular expressions, as well as in Java string literals. If you need a literal backslash in a regular expression, you need to double it twice. Try \\\\ (becomes \\ after lexed, becomes the literal \ for the regex parser).

+4
source share

You are trying to split a string into a backslash, you need to use:

 String regex = "\\\\"; 

\ is an escape character for both the Java string and the regex engine. Thus, the Java string \\ is passed to the regular expression engine as \ , which is incomplete because \ must be followed by the character that it is trying to escape.

The string \\\\ is passed to the regex engine as \\ , which is \ escaping a \ , which actually means literal \ .

+2
source share

You need to avoid the '\' char in regexp templates, so your regex will be

 String regex = "\\\\"; 
+2
source share

Replace

String regex = "\\";

from

String regex = "\\\\";

+2
source share

You must correct your regular expression. It should be:

 String regex = "\\\\"; 

because double backslash is an escape sequence for Java strings.

+2
source share

All Articles