简体   繁体   中英

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.

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");

You will need to escape the * since it is a special character in regular expressions.

So testString.replaceAll("__constant float\\\\* windowArray", "__global float\\\\* windowArray");

The * is a regex quantifier. The replaceAll method use regex. To avoid using regular expressions try using the replace method instead.

Example:

String testString = "__constant float* windowArray";
String replaceString = "__global float* windowArray";
String result = testString.replace(testString.subSequence(0, testString.length()-1), 
            replaceString.subSequence(0, replaceString.length()-1));
String result = testString.replaceAll("__constant float windowArray\\\\*", "__global float\\* windowArray");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM