简体   繁体   中英

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:

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

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);
}

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";     

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

Try this:

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

Your original input text should be

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

instead of

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

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]);      
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM