Reputation: 53
I have a string (say)
int t=5;
I want to replace the identifier 't'
in above string with some other String say "abc"
. using the replaceAll()
or replace()
methods of String in java replaces char 't' in int as well. so the output that i get is
"inabc abc=5;"
I want to replace the identifier only. please help me out. Thank you.
Upvotes: 0
Views: 258
Reputation: 21
Use the following regexp to replace all occurrences of a variable, assuming that before and after the name there cannot be any word-like character:
String s = "int t=5";
String s2 = s.replaceAll("(?<!\\w)t(?!\\w)", "abc");
Upvotes: 0
Reputation: 121830
You need to use the word anchor (\b
) as in:
s = s.replaceAll("\\bt\\b", "abc");
A regex has no notion of a word!
However, this will only ever bring you so far; this regex may fail on some more complicated constructs. You really want to use a parser if you want more complex substitutions; parboiled, for instance.
Upvotes: 5
Reputation: 41230
I think this would work-
yourString.replace(" t", " abc");
Upvotes: 1