How to Split String Without Regex [Duplicate]

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"?

5

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.

1

You can try this one.

String target = ".";
String someString = "123.456";
StringTokenizer tokenValue = new StringTokenizer(someString, target);

while (tokenValue.hasMoreTokens()) {
    System.out.println(tokenValue.nextToken());
}
1

String::split do split without regex if the regex is:

  • a one-char String and this character is not one of the RegEx's meta characters .$|()[{^?*+\\
  • two-char String and the first char is the backslash and the second is not the ascii digit or ascii letter.

Please see String::split() source code for details.

For escaped '.' target it is going to be split without regex.

1
Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest