Tim
Tim

Reputation: 2257

How do I replace all asterisks?

In Java, I want to replace all * characters with \*.

Example: Text: select * from blah

Result: select \\* from blah

public static void main(String[] args) {
    String test = "select * from blah";
    test = test.replaceAll("*", "\\*");
    System.out.println(test);
}

This does not work, nor does adding a escape backslash.

Upvotes: 15

Views: 32829

Answers (3)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298988

You don't need any regex functionality for this, so you should use the non-regex version String.replace(CharSequence, CharSequence):

String test = "select * from blah *asdf";
test = test.replace("*", "\\*");
System.out.println(test);

Upvotes: 12

RonU
RonU

Reputation: 5795

For those of you keeping score at home, and since understanding the answer may be helpful to someone else...

String test = "select * from blah *asdf";
test = test.replaceAll("\\*", "\\\\*");
System.out.println(test);

works because you must escape the special character * in order to make the regular expression happy. However, \ is a special character in a Java string, so when building this regex in Java, you must also escape the \, hence \\*.

This frequently leads to what amounts to double-escapes when putting together regexes in Java strings.

Upvotes: 8

Tim
Tim

Reputation: 2257

I figured it out

    String test = "select * from blah *asdf";
    test = test.replaceAll("\\*", "\\\\*");
    System.out.println(test);

Upvotes: 24

Related Questions