Using RegEx to change the date with string inbuilt function in java

I have a below code where I need to replace all “buyDate:YYYY-mm-dd” to current date using String.replaceAll method. Any suggestion how I can update date for only buyDate field, since I have some other date field so I cannot directly perform replace operation.

String str = content .replace("yyyy-mm-dd", LocalDate.now().toString());

I am using loading below data to string object which is stored in json file.

Json file:

    "id": 123,
    "test": {
        "id": "1",
        "name": "string"
    },
    "items": [
        {
            "id": "123",
            "manufactureDate":"2018-12-12"
            "product": {
                "id": "12345",
                "buyDate": "2019-04-15",
            },
            "Moreitems": [
                {
                    "id": "qwerty123",
                    "manufactureDate":"2018-12-12"
                    "product": {
                        "id": "qwerty345",
                        "buydate": "2019-04-15",
                }
            ]
        }
    ]
}```

Answer

You need to use a regular expression to match the search pattern. You can learn more about how to write regular expressions at http://www.regular-expressions.info/

Briefly:

  • s matches a white space character
  • d matches a digit
  • * means match the preceding token 0 or more times
  • {4} means match the preceding token exactly 4 times

The regular expression that matches a date is: d{4}-d{2}-d{2}. It means match four digits followed by dash then two digits then a dash then two digits.

Of course you need to escape the back-slack when you are writing a string literal in java. You also need to escape the double quotes.

String result = content.replaceAll("("buyDate"\s*:\s*"(\d{4}-\d{2}-\d{2})")", ""buyDate":" + LocalDate.now().toString() + """);

Leave a Reply

Your email address will not be published. Required fields are marked *