-1

I have to pars strings as one below:

String input = "{\"1\",\"2\",\"3\"}";

As an output I want to have an array of string with only numbers, something like that:

String[] output = new String[]{"1","2","3"};

My current working solution is:

String[] output = input.replaceAll("\\{|\\}|\"", "").split(",");

Are there any other solution that could do the same? More readable or relevant?

lczapski
  • 3,644
  • 3
  • 10
  • 26

4 Answers4

1

You could fetch all numbers instead of removing all special chars:

String input = "{\"1\",\"2\",\"3\"}";

List<String> matches = new ArrayList<>();

Matcher numberMatcher = Pattern.compile("\\d+").matcher(input);
while (numberMatcher.find()) {
  matches.add(numberMatcher.group());
}

Using

import java.util.regex.Matcher;
import java.util.regex.Pattern;
Eyal
  • 1,640
  • 1
  • 16
  • 31
1

Using x.replaceAll("\\D+", " ") from this answer which @Emre Acar suggested instead of your own regex might improve readability a bit. Other than that using split(",") is probably already the most readable way to do it.

I highly doubt that this is more readable than your solution, but if you want to do it in a "relevant" fancy way you could use streams:

    String input = "{\"1\",\"2\",\"3\"}";
    String[] output = Stream.of(input)
            .map(x -> x.replaceAll("\\D+", " "))
            .toArray(String[]::new);
    System.out.println("output: " + Arrays.toString(output));
    // output: [ 1 2 3 ]
T A
  • 1,488
  • 4
  • 15
  • 25
0

Your solution is the simplest. Just for fun, here is a solution that also verifies that the input string is syntactically correct:

private static final Pattern OUTER = Pattern.compile("\\{(.*)\\}");
private static final Pattern INNER = Pattern.compile("\\\"(\\d+)\\\"(?:,(.*))?");

...

    String input = "{\"1\",\"2\",\"3\"}";
    Matcher matcher = OUTER.matcher(input);
    if (!matcher.matches()) {
        // Syntax error
    } else {
        List<String> list = new ArrayList<>();
        input = matcher.group(1);
        while (input != null) {
            matcher = INNER.matcher(input);
            if (!matcher.matches()) {
                // Syntax error
            } else {
                list.add(matcher.group(1));
                input = matcher.group(2);
            }
        }
        String[] output = list.toArray(new String[list.size()]);
    }
Maurice Perry
  • 7,501
  • 2
  • 9
  • 19
-1

You could try input.replaceAll(",", "").substring(1, input.length - 1).split("\"")

First you remove the commas from the string by replacing them with empty strings, then you remove the brackets by leaving out the first and the last character and finally you split at the escaped apostrophes (though this might end you up with empty entries in your finaly Array, so you need to catch these. I will think about a sloution that doesn't do that).

TigersEye120
  • 158
  • 15