• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to Replace a substring with another..??  RSS feed

 
Naveen Raja
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I want to replace part of string with another..for example i have a string like "HI_ROUTING_DATA[0]=DEFAULT"...and i want to replace the substring "[0]=" with "@"....So the resultant string should be "HI_ROUTING_DATA@DEFAULT"i try with the following piece of code...but it is not giving the proper output...


String line1 = "HI_ROUTING_DATA[0]=DEFAULT"
String pat = "[0]=";

try
{


System.out.println("Pattern is "+pat);

p = Pattern.compile (pat);
}


catch (PatternSyntaxException e)
{

System.out.println("Exception occured");

return("Exception");
}


Matcher m = p.matcher (line1);

String result = m.replaceAll("@");

System.out.println(result);


Thanks a lot in Advance......
 
Aditya Kumar
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not simply try this?
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but it is not giving the proper output...

So what output DOES it produce? When asking questions, always tell in detail what you were expecting, and what is actually happening.

My hunch would be that it doesn't work becauase rectangular brackets are special characters in regexps, which need to be escaped when used literally. "pat" should probably be "\\[0\\]=".
 
Aditya Kumar
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From what I see here, I gather that you want to replace a substring (having the pattern "[integer]") with some other string (like "@"). In that case, you cant use the string.replaceAll() method, something which I had suggested in my last post here.

I wrote this code below. It will replace the pattern "[integer]" (strings like "[0]" and "[12]") to any string that you may wish to. Here it is:


I hope this solves your problem.

Meanwhile, please try and be more precise with your problems here. As mentioned by Ulf Dittmer, try and be detailed. It helps waste less time.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!