developer033 developer033 - 6 months ago 10
Java Question

Split a string with restrictions

I want to split a string, but I want to split it removing the numbers and of course, the character that follows it, that are not equals the specified number.

Here's my code:

public static void main(String[] args) throws IOException {
String x = "32 X 28 Y 32 X 40 Y 36 X 32 Y 32 X 24 X 32 X";
System.out.println(splittedArray(x, "\\s(?<!32)\\s").toString());
// I know this regex is completely wrong.
}

private static List<String> splittedArray(String str, String regex) {
return Arrays.asList(str.split(regex));
}


A better explanation:

Sample:

32 X 28 Y 32 X 40 Y 36 X 32 Y 32 X 24 X 32 X


If I want all 32 numbers and the character that follows, it should return:

32 X or 32X // Whatever
32 X
32 Y
32 X
32 X


I'm stuck to make it work, any help will be appreciated.

Answer

I would tackle it using the Pattern and Matcher, rather than attempting to split the String.

Edit: updated the code to show how to collect into a List<String> and convert to String[] if desired.

public static void main(String[] args)
{
    // the sample input
    String x = "32 X 28 Y 32 X 40 Y 36 X 32 Y 32 X 24 X 32 X";

    // match based upon "32". This specific match can be made into
    // a String concat so the specific number may be specified
    Pattern pat = Pattern.compile("[\\s]*(32\\s[^\\d])");

    // get the matcher
    Matcher m = pat.matcher(x);

    // our collector
    List<String> res = new ArrayList<>();

    // while there are matches to be found
    while (m.find()) {
        // get the match
        String val = m.group().trim();
        System.out.println(val);

        // add to the collector
        res.add(val);
    }

    // sample conversion
    String[] asArray = res.toArray(new String[0]);
    System.out.println(Arrays.toString(asArray));
}

Returned Output based upon the sample input:

32 X
32 X
32 Y
32 X
32 X
[32 X, 32 X, 32 Y, 32 X, 32 X]