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?
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.
A character with a backslash (\) just before it is an escape sequence or escape character.
The character '\' is a special character and needs to be escaped when used as part of a String, e.g., "\".
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.
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.
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