Borgy Manotoy
Borgy Manotoy

Reputation: 2038

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!

Upvotes: 1

Views: 718

Answers (2)

Jos
Jos

Reputation: 2013

You could build the output using a StringBuilder like below, Please refer to JavaDoc for appendReplacement for info on how this works.

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

    StringBuilder sb = new StringBuilder();

    while (matcher.find()) {
        String s2 = matcher.group(0);
        int workYear = Integer.parseInt(s2.replaceAll("[^0-9]", ""));
        matcher.appendReplacement(sb, String.valueOf(workYear));
    }
    matcher.appendTail(sb);

    String result = sb.toString();

Upvotes: 1

vavasthi
vavasthi

Reputation: 952

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);

Upvotes: 1

Related Questions