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.
When you call the
replaceAll()method, it returns a newStringwith the modified value – it doesn’t change the originalString.Your code should therefore be…
or even this…
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 tom = p.matcher(sb.toString());, and clear yourStringBuffer, so that you’re feeding the result of the first modification into the secondp.matcher()method, and to remove theduplicatein the output. Something like this…But, as I said, it’d be much better and simpler to just use
replaceAll().