2

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.

2
  • Wow. The more I learn about Java the more I like C#. Commented Nov 5, 2010 at 21:07
  • possible duplicate of Backslash problem with String.replaceAll Commented May 26, 2011 at 8:32

4 Answers 4

7

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");
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Or, if manual escaping is not feasible (e.g. when building a pattern at runtime), use Pattern.quote(String) and Matcher.quoteReplacement(String).
2

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.