Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:
like image 866
GVillani82 Avatar asked Dec 26 '22 15:12

GVillani82


1 Answers

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
like image 199
PermGenError Avatar answered Jan 08 '23 15:01

PermGenError