Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 721
smuggledPancakes Avatar asked Jul 25 '26 11:07

smuggledPancakes


1 Answers

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");
like image 67
Gregg Avatar answered Jul 27 '26 00:07

Gregg