Java Json String extract number and replace specific text

I have a text file in json, and I want to replace NumberInt(x) with the number x.

In the text file, there are records/data which is in json that has a field workYear: NumberInt(2010) as an example.

I want to replace this into workYear: 2010 by removing NumberInt( and ). This NumberInt(x) is located anywhere in text file and I want to replace all of it with its number.

I can search all the occurences of this, but I am not sure how to replace it with just the number value.

String json = <json-file-content>

String sPattern = "NumberInt\\([0-9]+\\)";
Pattern pattern = Pattern.compile(sPattern);
Matcher matcher = pattern.matcher(json);

while (matcher.find()) {
    String s = matcher.group(0);
    int workYear = Integer.parseInt(s.replaceAll("[^0-9]", ""));
    System.out.println(workYear);
}

I would like to replace all the NumberInt(x) with just the number value int json String... then I will update the text file (json file).

Thanks!

Answer:1

Following should work. You need to capture the tokens.

    String json = "workYear:NumberInt(2010) workYear:NumberInt(2011)";
    String sPattern = "NumberInt\\(([0-9]+)\\)";
    Pattern pattern = Pattern.compile(sPattern);
    Matcher matcher = pattern.matcher(json);

    List<String> numbers = new ArrayList<>();
    while (matcher.find()) {
        String s = matcher.group(1);
        numbers.add(s);
    }
    for (String number: numbers) {

        json = json.replaceAll(String.format("NumberInt\\(%s\\)", number), number);
    }
    System.out.println(json);
Answer:2

I have a table from which I want to fetch all data on behalf of a specific column and then want to save that data in form of JSON so that I can send it over API to the database for saving. I am ...

I was wondering if someone could help append data to an XML file. Below, I have code where it grabs data from another xml file, does some logic changing, and writes the changes to a new output file. ...

Is it possible to identify, probably using reflection, whether some method within a specific java class calls another method at build time? Let's say that I have ClassA that declares methodA1() ...

I am using Apache Active MQ with Spring..... the problem I am facing is that I am creating producer on one machine let say Machine1 and I am creating one consumer on second machine let say Machine2... ...