Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String replace for URLs

 
Jitesh Sinha
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to replace a URL inside a text file.I have taken the contents of the text file into a String variable "content".
The example code is as below :-

String urlToReplace = "/en/US/products/afile.html" ;
String newUrl = "http://myserver/LA/es/customer/afile.html" ;

String content1 = content.replace(urlToReplace,newUrl) ;

The above statement results in replacing only "afile.html" part of the variable urlToReplace with the whole of newUrl.
So content1 now has "/en/US/products/http://myserver/LA/es/customer/afile.html" instead of expected "http://myserver/LA/es/customer/afile.html" .As you can see only the part after last "/" is getting matched and replaced.Even Pattern class usage does the same thing.

What am I doing wrong?
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I want you to try like this,
Just replace the single '/' by double '//'.

Like



with this new,



Its a silly guess, but give it a try !!
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I am not mistaken..

String content1 = content.replace(urlToReplace,newUrl);

means, replace all substrings of "content" that match urlToReplace with newUrl

so what are the contents of "content" here?
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gamini Sirisena wrote:

so what are the contents of "content" here?


Jitesh wrote:
I have taken the contents of the text file into a String variable "content".
 
Stephen Davies
Ranch Hand
Posts: 352
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think Sagar has it, try this:




To test this, I wrote a quick class as follows. It compiles and runs fine giving you the new URL as the output.



Give it a go.
 
Jitesh Sinha
Ranch Hand
Posts: 146
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guyz,it seems the replace method works as expected.It replaces the whole string as anyone would expect.There is absolutely no catch in that.
I found that there is some other piece of the code which was mingling with URLs and that was what created confusion.I had to spend 8-10 hours debugging this problem and to find out the root cause.

Sorry for wasting your time guyz.Thanks for lending a helping hand.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic