Java String to Array Splitting

Nan*_*ana 1 java split

我有一个字符串,例如: "My brother, John, is a handsome man."

我想将其拆分为一个数组,使输出为:

"My" , "brother", "," , "John", "," , "is", "a", "handsome", "man", "."
Run Code Online (Sandbox Code Playgroud)

谁能帮我这个?我需要在Java上执行此操作.

The*_*ind 5

的组合replaceAll(),并split()应该这样做.

public static void main(String[] args) {
    String s ="My brother, John, is a handsome man.";
    s = s.replaceAll("(\\w+)([^\\s\\w]+)", "$1 $2");  // replace "word"+"punctuation" with "word" + <space> + "punctuation" 
    String[] arr = s.split("\\s+"); // split based on one or more spaces.
    for (String str : arr)
        System.out.println(str);
}
Run Code Online (Sandbox Code Playgroud)

O/P:

My
brother
,
John
,
is
a
handsome
man
.
Run Code Online (Sandbox Code Playgroud)