user3425778
user3425778

Reputation: 53

replacing particular set of characters from a string in java

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

Answers (4)

Costin G.
Costin G.

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

Storm Qi
Storm Qi

Reputation: 1

I think you can change "t=" to "abc=".

str.replace("t=", "abc=");

Upvotes: -1

fge
fge

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

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

I think this would work-

yourString.replace(" t", " abc");

Upvotes: 1

Related Questions