Car981
Car981

Reputation: 261

java regex to match variable

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.

Upvotes: 2

Views: 296

Answers (2)

Andrzej Doyle
Andrzej Doyle

Reputation: 103777

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"

Upvotes: 0

assylias
assylias

Reputation: 328568

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

Upvotes: 1

Related Questions