10

So I wrote a little section of code in a program of mine that uses the split method to parse out and sort the individual components held within a string. Below is a sample of the code:

String[] sArray;

String delimiter = "*";

String test = "TEXT*TEXT*TEXT*";
String a = "";
String b = "";
String c = "";

sArray= test.split(delimiter);

a = sArray[0];
b = sArray[1];
c = sArray[2];

System.out.println("A is: " + a + "\nB is: " + b + "\nC is: " + c);

However, when I run this program, it returns an error stating that:

Dangling meta character '*' near index 0

So I googled this error and found it might be related to an issue with how * can be considered a wildcard character in regex. So I tried:

String delimiter = "\*"

But that just returned another error stating:

illegal escape character

Has anyone ran into this issue before or know how you are (if you are) supposed to escape * in java?

This 0ne Pr0grammer
  • 2,632
  • 14
  • 57
  • 81
  • Note (Jan. 2018), raw string literals might be coming for Java (JDK 10 or more): see [In Java, is there a way to write a string literal without having to escape quotes?](https://stackoverflow.com/a/48481601/6309). – VonC Jan 27 '18 at 23:27

3 Answers3

25

You also have to escape the backslash:

String delimiter = "\\*";

Because the string literal "\\" is just a single backslash, so the string literal "\\*" represents an escaped asterisk.

jlordo
  • 37,490
  • 6
  • 58
  • 83
5

The way to understand the solution is to realize that there are two "languages" in play here. You have the language of regular expressions (Java flavour) in which * is a meta-character that needs to be escaped with a \ to represent a literal *. That gives you

''\*''    // not Java yet ...

But you are trying to represent that string in the "language" of Java String literals where a \ is the escape character. So that requires that any literal \ (in whatever it is we are trying to represent) must be escaped. This gives you

"\\*"     // now Java ...

If you apply this approach/thinking consistently - "first do the regex escaping, then do the String literal escaping" - you won't get confused.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
-1

You will have to attach "\" before "*" as if you want to represent "\" in java you have to use one more "\" before it.

So, "\" represents:-----> "\" So if you want to use "" as delimiter the use "\"

Corrected Code:

String delimiter = "\\*";
String test = "TEXT*TEXT*TEXT*";
String a = "";
String b = "";
String c = "";
sArray= test.split(delimiter);
a = sArray[0];
b = sArray[1];
c = sArray[2];
System.out.println("A is: " + a + "\nB is: " + b + "\nC is: " + c);

OUTPUT:

A is: TEXT

B is: TEXT

C is: TEXT