8

Can somebody 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 at the 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)
1
  • I think you might need "///" in your regexp... Commented Mar 10, 2011 at 9:09

6 Answers 6

23

When you type "\\", this is actually a single backslash (due to escaping special characters in Java Strings).

Regular expressions also use backslash as special character, and you need to escape it with another backslash. So in the end, you need to pass "\\\\" as pattern to match a single backslash.

Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

2

You are trying to split the string on a back slash, you need to use:

String regex = "\\\\";

\ is the escape character for both Java string and the regex engine. So a Java string \\ is passed on to the regex engine as \ which is incomplete as \ has to be followed by the character that it is trying to escape.

The String \\\\ is passed on to the regex engine as \\ which is a \ escaping a \ which effectively means a literal \.

Comments

2

You have to escape '\' char in regexp patterns, so your regex basically will be

String regex = "\\\\";

Comments

2

Replace

String regex = "\\";

with

String regex = "\\\\";

Comments

2

You must fix your regex. It ought to be:

String regex = "\\\\";

because the double backslash is an escape sequence for Java Strings.

1 Comment

LOL, I see I've not been as fast as I thought :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.