Gopi
Gopi

Reputation: 237

Replacing a string using replaceAll or Pattern Matcher

I need to replace a string having say for example "8:00 AM - 5:00 PM" with "8:00 AM ET - 5:00 PM ET"

I have tried the following code but it doesn't work...

time.replaceAll("AM", "AM ET");
time.replaceAll("PM", "PM ET");
convertedTime = time;
System.out.println(convertedTime); // didnt get replaced

I tried below way and its working but not getting replaced properly,

Pattern p = Pattern.compile("(AM)");
Matcher m = p.matcher(time);
StringBuffer sb = new StringBuffer(); 
while(m.find()) {
    m.appendReplacement(sb, "AM ET");
    } 
m.appendTail(sb); 
p = Pattern.compile("(PM)");
m = p.matcher(time);
while(m.find()) {
    m.appendReplacement(sb, "PM ET");
    } 
m.appendTail(sb); 

System.out.println("sb: " + sb); // coming as sb: 8:00 AM ET - 5:00 PM8:00 AM - 5:00 PM ET

Please let me know why the first approach did not work, and if it possible to correct in second approach.

Upvotes: 1

Views: 8001

Answers (2)

wattostudios
wattostudios

Reputation: 8774

When you call the replaceAll() method, it returns a new String with the modified value - it doesn't change the original String.

Your code should therefore be...

String convertedTime = time.replaceAll("AM", "AM ET");
convertedTime = convertedTime.replaceAll("PM", "PM ET");
System.out.println(convertedTime);

or even this...

String convertedTime = time.replaceAll("AM", "AM ET").replaceAll("PM", "PM ET");
System.out.println(convertedTime);

Due to the simplicity of the above code, I wouldn't really suggest that you use your Pattern-based code - its just too overly-complicated to achieve the same result. However, seeing as though you asked, you would probably just need to change your m = p.matcher(time); line to m = p.matcher(sb.toString());, and clear your StringBuffer, so that you're feeding the result of the first modification into the second p.matcher() method, and to remove the duplicate in the output. Something like this...

Pattern p = Pattern.compile("(AM)");
Matcher m = p.matcher(time);
StringBuffer sb = new StringBuffer(); 
while(m.find()) {
    m.appendReplacement(sb, "AM ET");
    } 
m.appendTail(sb); 
p = Pattern.compile("(PM)");
m = p.matcher(sb.toString()); // CHANGED
sb = new StringBuffer(); // ADDED
while(m.find()) {
    m.appendReplacement(sb, "PM ET");
    } 
m.appendTail(sb); 

System.out.println("sb: " + sb);

But, as I said, it'd be much better and simpler to just use replaceAll().

Upvotes: 7

Juvanis
Juvanis

Reputation: 25950

Try re-assigning the returned Strings from the methods. e.g. time = time.replaceAll("AM", "AM ET");

Upvotes: 2

Related Questions