Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split String without regex [duplicate]

Tags:

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:

  1. A way to split into an array by a non-regex target
  2. 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"?

like image 261
birgersp Avatar asked Aug 19 '16 11:08

birgersp


People also ask

How split a string in regex?

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.

Is regex faster than string split?

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.

How do you split a string into two strings?

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.

What does \\ mean in Java regex?

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.


1 Answers

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.

like image 115
Tim Hallyburton Avatar answered Oct 11 '22 10:10

Tim Hallyburton