Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do You Need To Escape * Character in Java?

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?

like image 979
This 0ne Pr0grammer Avatar asked Jan 07 '13 22:01

This 0ne Pr0grammer


People also ask

Is an asterisk a special character in Java?

The * is a reserved symbol on the command line. Save this answer. Show activity on this post. The shell replaces * with the list of the files in the current directory.

How do you escape a character in Java?

A character with a backslash (\) just before it is an escape sequence or escape character.

What is an illegal escape character in Java?

The character '\' is a special character and needs to be escaped when used as part of a String, e.g., "\".


2 Answers

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.

like image 113
jlordo Avatar answered Oct 21 '22 21:10

jlordo


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.

like image 32
Stephen C Avatar answered Oct 21 '22 21:10

Stephen C