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:
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"?
To split a string by a regular expression, pass a regex as a parameter to the split() method, e.g. str. split(/[,. \s]/) . The split method takes a string or regular expression and splits the string based on the provided separator, into an array of substrings.
Regex. Split is more capable, but for an arrangement with basic delimitting (using a character that will not exist anywhere else in the string), the String. Split function is much easier to work with. As far as performance goes, you would have to create a test and try it out.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With