GVillani82
GVillani82

Reputation: 17429

Splitting String using split method

I want split a string like this:

  C:\Program\files\images\flower.jpg     

but, using the following code:

  String[] tokens = s.split("\\");
  String image= tokens[4];

I obtain this error:

 11-07 12:47:35.960: E/AndroidRuntime(6921): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1:

Upvotes: 4

Views: 893

Answers (7)

PermGenError
PermGenError

Reputation: 46398

try

String s="C:\\Program\\files\\images\\flower.jpg"

String[] tokens = s.split("\\\\");

In java(regex world) \ is a meta character. you should append with an extra \ or enclose it with \Q\E if you want to treat a meta character as a normal character.

below are some of the metacharacters

<([{\^-=$!|]})?*+.>

to treat any of the above listed characters as normal characters you either have to escape them with '\' or enclose them around \Q\E

like:

        \\\\ or \\Q\\\\E

Upvotes: 5

Arham
Arham

Reputation: 2102

This works,

    public static void main(String[] args) {
        String str = "C:\\Program\\files\\images\\flower.jpg";
        str = str.replace("\\".toCharArray()[0], "/".toCharArray()[0]);
        System.out.println(str);
        String[] tokens  = str.split("/");
        System.out.println(tokens[4]);      
    }

Upvotes: 0

Shahinoor Shahin
Shahinoor Shahin

Reputation: 685

Try this:

String s = "C:/Program/files/images/flower.jpg";
String[] tokens = s.split("/");
enter code hereString image= tokens[4];

Upvotes: 1

Venkatesh S
Venkatesh S

Reputation: 5494

String[] tokens=s.split("\\\\");

Upvotes: 1

Esailija
Esailija

Reputation: 140210

There is 2 levels of interpreting the string, first the language parser makes it "\", and that's what the regex engine sees and it's invalid because it's an escape sequence without the character to escape.

So you need to use s.split("\\\\"), so that the regex engine sees \\, which in turn means a literal \.

If you are defining that string in a string literal, you must escape the backslashes there as well:

String s = "C:\\Program\\files\\images\\flower.jpg";     

Upvotes: 1

mmalmeida
mmalmeida

Reputation: 1057

You need to split with \\\\, because the original string should have \\. Try it yourself with the following test case:

    @Test
public void split(){
      String s = "C:\\Program\\files\\images\\flower.jpg";     


        String[] tokens = s.split("\\\\");
        String image= tokens[4];
        assertEquals("flower.jpg",image);
}

Upvotes: 2

Ahmad
Ahmad

Reputation: 12707

Your original input text should be

 C:\\Program\\files\\images\\flower.jpg  

instead of

 C:\Program\files\images\flower.jpg  

Upvotes: 0

Related Questions