Search code examples
javastringapireplaceall

Why does this Java String.replaceAll() code not work?


I have used string.replaceAll() in Java before with no trouble, but I am stumped on this one. I thought it would simply just work since there are no "/" or "$" characters. Here is what I am trying to do:

String testString = "__constant float* windowArray";
String result = testString.replaceAll("__constant float* windowArray", "__global float* windowArray");

The variable result ends up looking the same as testString. I don't understand why there is no change, please help.


Solution

  • The first argument passed to replaceAll is still treated as a regular expression. The * character is a special character meaning, roughly, the previous thing in the string (here: t), can be there 0 or more times. What you want to do is escape the * for the regular expression. Your first argument should look more like:

    "__constant float\\* windowArray"
    

    The second argument is, at least for your purposes, still just a normal string, so you don't need to escape the * there.

    String result = testString.replaceAll("__constant float\\* windowArray", "__global float* windowArray");