0

I have one string I want to find out all date values and relace them with specific string.

My code looks like:

String mydata = "{[... \"date\":\"2016-03-16T12:38:28.390Z\"]},{[ ... \"date\":\"2016-03-16T12:38:28.390Z\" ...]}";
        Pattern pattern = Pattern.compile("");
        Matcher matcher = pattern.matcher(mydata);
        while(matcher.find()){
            mydata = mydata.replace(matcher.group(), matcher.group().substring(0, 10));
        }
        System.out.println(mydata);

What string regex I should pass in Pattern.compile("");?

My output should look like:

{[... "date":"2016-03-16"]},{[ ... "date":"2016-03-16" ...]}
Shashi Ranjan
  • 1,491
  • 6
  • 27
  • 52

3 Answers3

0
import org.json.*;


JSONObject obj = new JSONObject("{[... "date":"2016-03-16"]},{[ ... "date":"2016-03-16" ...]}");

The rest of the code depends on your json-structure. Have a look at:

How to parse JSON in Java

or

Java Api Link JsonObject

Community
  • 1
  • 1
osanger
  • 2,276
  • 3
  • 28
  • 35
0

I am not sure about T and Z from input. If they are same always, then below regex will work. If T and Z not constant then change T and Z by [A-Z] in regex.

one more change i did, replaced

mydata = mydata.replace(matcher.group(), matcher.group().substring(0, 10));

by

mydata = matcher.replaceAll("");

It getting required output.

String mydata = "{[\"date\":\"2016-03-16T12:38:28.390Z\"]},{[\"date\":\"2016-03-16T12:38:28.390Z\"]}";

Pattern pattern = Pattern.compile("T\\d{2}\\:\\d{2}\\:\\d{2}\\.\\d{3}Z");

Matcher matcher = pattern.matcher(mydata);
while(matcher.find()){
   mydata = matcher.replaceAll("");
}
System.out.println(mydata);
Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
0

If you want a regex based solution this seems to work for your example

Pattern pattern = Pattern.compile("(\\{\\[.*?\"date\":\"\\d{4}\\-\\d{2}\\-\\d{2}).*?(\"\\]\\})");
Matcher matcher = pattern.matcher(mydata);

while(matcher.find()) {
    System.out.println(matcher.group(1) + matcher.group(2));
}

IDEONE DEMO

rock321987
  • 10,942
  • 1
  • 30
  • 43