2

I have the name of a java variable in a string. I want to replace it with the letter x. How can I do this java, and make sure that other words in the string are not replaced ?

For example, say my variable is res, and my string is "res = res + pres + resd + _res. I want the string to become x = x + pres + resd + _res.

2 Answers 2

1

You can use a word boundary to only capture whole words:

String s = "res = res + pres + resd + _res";
String var = "res";
System.out.println(s.replaceAll("\\b" + var + "\\b", "x"));

outputs x = x + pres + resd + _res

Sign up to request clarification or add additional context in comments.

4 Comments

I really want any correct way to create a variable (as allowed by the language itself) to be taken into account. I added _res in my original post to reflect this example. "res=res+pres" should also work, even though there are no spaces
@Car981 The code I propose will work with _res or res=res+pres too.
Okay, will it also work with dollar signs, numbers, and basically anything that is given here: docs.oracle.com/javase/tutorial/java/nutsandbolts/… ?
@Car981 Yes it should - note that the list of valid characters provided in that link is far from exhaustive.
0

You can use the \b metacharacter to match a word boundary. (Bear in mind you'll need to use doule backslashes to escape this in Java.)

So you can do something like the following:

final String searchVar = "res";
final String replacement = "x";
final String in = "res = res + pres + resd + _res";

final String result = in.replaceAll("\\b" + searchVar + "\\b", replacement);
System.out.println(result);
// prints "x = x + pres + resd + _res"

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.