Split a string using the split method

I want to split the line as follows:

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

but using the following code:

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

I get 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: 
+4
source share
7 answers

try

 String s="C:\\Program\\files\\images\\flower.jpg" String[] tokens = s.split("\\\\"); 

In java (regex world) \ is a metacharacter. you must add with an additional \ or enclose it in \ Q \ E if you want to treat the metacharacter as a regular character.

Below are some metacharacters

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

to treat any of the listed characters as normal characters, you either need to avoid them with '\' or wrap them around \ Q \ E

as:

  \\\\ or \\Q\\\\E 
+5
source

You need to split by \\\\ , because the source string must 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); } 
+2
source

There are 2 levels of string interpretation, first the language parser makes it "\" , and that the regular expression engine sees and is invalid because it is an escape sequence without a character to be executed.

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

If you define this string in a string literal, you should also avoid backslashes:

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

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

+1
source

Try the following:

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

Your source should be

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

instead

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

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

Source: https://habr.com/ru/post/1444570/


All Articles