GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Replace any string between two substrings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Replace any string between two substrings" Watch "Replace any string between two substrings" New topic
Author

Replace any string between two substrings

Arun Suresh
Greenhorn

Joined: Sep 02, 2008
Posts: 18
Hi All,

I have a string
String a = "-d -k dfgherewrdjyfdf\"";
where 'dfgherewrdjyfdf' is a password of unknown length.
I want to replace dfgherewrdjyfdf with *****.
so that the final string looks like:
-d -k *****"
preferably i will like to replace anything between -k and ".
i could not find any one go solution with replaceall, regex or anywhere...

any help will be appreciated.

Arun
[ November 24, 2008: Message edited by: Arun Suresh Kumar ]
Roland Maurer
Greenhorn

Joined: Nov 23, 2008
Posts: 17
hello,

this should work :

String a = "-d -k dfgherewrdjyfdf\"";
a = a.replace(a.substring(a.indexOf("-k") + 2, a.lastIndexOf("\"")), " *********");
System.out.println(a);
Arun Suresh
Greenhorn

Joined: Sep 02, 2008
Posts: 18
Excellent.
That worked perfectly.
Your help is highly appreciated.
Thanks,
Arun
Roland Maurer
Greenhorn

Joined: Nov 23, 2008
Posts: 17
That worked perfectly

thats good
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

You'd like to check for absence of the sub strings. If indexOf or lastIndexOf returns -1 you will get a StringIndexOutOfBoundsException.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
Arun Suresh
Greenhorn

Joined: Sep 02, 2008
Posts: 18
Thankyou everyone who has replied.
ciao
cheers
Arun
 
GeeCON Prague 2014
 
subject: Replace any string between two substrings