gromit190 :
In my Java application I need to find indices and split strings using the same "target" for both occasions. The target is simply a dot.
Finding indices (by indexOf and lastIndexOf) does not use regex, so
String target = ".";
String someString = "123.456";
int index = someString.indexOf(target); // index == 3
gives me the index I need.
However, I also want to use this "target" to split some strings. But now the target string is interpreted as a regex string. So I can't use the same target string as before when I want to split a string...
String target = ".";
String someString = "123.456";
String[] someStringSplit = someString.split(target); // someStringSplit is an empty array
So I need either of the following:
- A way to split into an array by a non-regex target
- A way to "convert" a non-regex target string into a regex string
Can someone help? Would you agree that it seems a bit odd of the standard java platform to use regex for "split" while not using regex for "indexOf"?
Tim Hallyburton :
You need to escape your "target" in order to use it as a regex. Try
String[] someStringSplit = someString.split(Pattern.quote(target));
and let me know if that helps.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=451489&siteId=1