Do You Need To Escape * Character in Java?

15,053

Solution 1

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.

Solution 2

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.

Share:
15,053
This 0ne Pr0grammer
Author by

This 0ne Pr0grammer

Updated on June 08, 2022

Comments

  • This 0ne Pr0grammer
    This 0ne Pr0grammer about 2 years

    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?