Guava splitter for splitting on space,special character, digit

1.2k Views Asked by At

Can we create a guava splitter which splits in following way:

abc8 => abc + 8
a-b => a + b
a b => a + b
a,b => a + b
abc8 d => abc + 8 + d

?

2

There are 2 best solutions below

0
On BEST ANSWER

You don't even need Guava for this sort of thing. A simple String.split will do. Use the following regex:

(?=\d)|\W

For example:

"abc8".split("(?=\\d)|\\W")

If you must use Guava to tackle the problem, please beware that the Guava Splitter is buggy on look-ahead operations. As a work-around you can append a space character to your String and ignore the last match in the split results:

Splitter.onPattern("(?=\\d)|\\W").split("abc8 ") // result: [abc, 8, ]
0
On

I think this is what you are asking for. I'm not sure if there is a more efficient way to do it.

        String text = "abc-de+f8gsdf12345=";
        boolean lastWasLetter = false;
        boolean lastWasNumber = false;
        for(int i = text.length()-1; i >= 0; i--) {
            if(!Character.isLetterOrDigit(text.charAt(i))) {
                text = text.substring(0, i) + "-" + text.substring(i+1); // Replace special char with "-".
                lastWasLetter = false;
                lastWasNumber = false;
            } else if(Character.isLetter(text.charAt(i))) {
                if(lastWasNumber) {
                    text = text.substring(0, i+1) + "-" + text.substring(i+1); // Add a "-" between a digit and a letter.
                }
                lastWasLetter = true;
                lastWasNumber = false;
            } else { // The char is a digit.
                if(lastWasLetter) {
                    text = text.substring(0, i+1) + "-" + text.substring(i+1); // Add a "-" between a digit and a letter.
                }
                lastWasLetter = false;
                lastWasNumber = true;
            }
        }
        System.out.println("Converted text: " + text);
        System.out.println("Splitted text text: ");
        String[] parts = text.split("-");
        for(String part : parts) {
            System.out.println(part);
        }