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

空扰寡人 提交于 2019-12-12 19:01:23

问题


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.


回答1:


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



回答2:


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

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




回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/4109925/why-does-this-java-string-replaceall-code-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!