1

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!

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

This seems to work, but it is not using StringBuilder... only StringBuffer. Also, It stopped on line 75439 still checking why it stopped there but it did not get any error.
is it the last line? i added matcher.appendTail(sb); to appen any remaining text to Builder/Buffer.. Also, if input is very large, you could split by lines and do this and merge lines.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.