Search code examples
javaregexreplaceall

How to find and update properties embedded in a String in Java


I am trying to find and update the values of a string. The string is a recurrence rule sent by a client which I need to get the until property and add time to it. (Ps the setTime/setHour... is depricated)

What i have is:

import java.util.Calendar;


public class TestReplaceString {

/**
 * @param args
 */
public static void main(final String[] args) {

     String originalRecurrenceRule = "FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;WKST=MO;UNTIL=20160731T223030Z;";
    System.out.println("Unformated: " + originalRecurrenceRule);



    System.out.println("Formated: " + originalRecurrenceRule.replaceAll("UNTIL.*?Z", "UNTIL=" + "sameDateAsPassedByTheCLient" + "T235959Z;"));

}

The problem with this is that I need to keep the date supplied by the client and only add time eg

The date 20170101T220000Z would become 20170101T235959Z

What i was trying to accomplish is something like a validator to get the property UNTIL from the string and change it. Any suggestions are welcome.

Kind Regards


Solution

  • Something like this might be a bit more suitable:

    String originalRecurrenceRule = "FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;WKST=MO;UNTIL=20160731T223030Z;";
    String until = originalRecurrenceRule.substring(originalRecurrenceRule.indexOf("UNTIL"), originalRecurrenceRule.indexOf(";", originalRecurrenceRule.indexOf("UNTIL")));
    SimpleDateFormat sdf = new SimpleDateFormat();
    Date date = sdf.parse(until.substring(until.indexOf("=") + 1),until.length() - 1);
    date.setTime(timeInMilliseconds);
    originalRecurrenceRule.replace(until, "UNTIL="+ date.toString() + ";");