0

I am trying to split each string from a paragraph, which has proper grammar based punctuation delimiters like ,.!? or more if any.

I am trying to achieve this using Java. Here is my code.

private void printWords(String inputString) {
        String[] x = inputString.split("[.!,\\s]");
        for(String temp: x){
            System.out.println(temp);
        }

    }

Sample input String:

He is srk. Oh! I am a very good friend of srk.

My output:

He
is
srk

Oh

I
am
a
very
good
friend
of
srk

There is a problem here, It is having spaces as shown in the output. What should be my regular expression to split strings in any given paragraph, without spaces in the output.

srk
  • 4,857
  • 12
  • 65
  • 109

2 Answers2

4

You need to add a + to make your expression match one or more characters:

String[] x = inputString.split("[.!,\\s]+");
Keppil
  • 45,603
  • 8
  • 97
  • 119
2

What about:

String[] x = inputString.split("\\W+");
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148