How do I split a string with any whitespace chars

2018-12-31 03:28发布

What regex pattern would need I to pass to the java.lang.String.split() method to split a String into an Array of substrings using all whitespace characters (' ', '\t', '\n', etc.) as delimiters?

12条回答
临风纵饮
2楼-- · 2018-12-31 04:15

In most regex dialects there are a set of convenient character summaries you can use for this kind of thing - these are good ones to remember:

\w - Matches any word character.

\W - Matches any nonword character.

\s - Matches any white-space character.

\S - Matches anything but white-space characters.

\d - Matches any digit.

\D - Matches anything except digits.

A search for "Regex Cheatsheets" should reward you with a whole lot of useful summaries.

查看更多
像晚风撩人
3楼-- · 2018-12-31 04:16

I'm surprised that nobody has mentioned String.split() with no parameters. Isn't that what it's made for? as in:

"abc def ghi".split()
查看更多
君临天下
4楼-- · 2018-12-31 04:16

you can split a string by line break by using the following statement :

 String textStr[] = yourString.split("\\r?\\n");

you can split a string by Whitespace by using the following statement :

String textStr[] = yourString.split("\\s+");
查看更多
看风景的人
5楼-- · 2018-12-31 04:18

"\\s+" should do the trick

查看更多
孤独寂梦人
6楼-- · 2018-12-31 04:23

Also you may have a UniCode non-breaking space xA0...

String[] elements = s.split("[\\s\\xA0]+"); //include uniCode non-breaking
查看更多
临风纵饮
7楼-- · 2018-12-31 04:23
String string = "Ram is going to school";
String[] arrayOfString = string.split("\\s+");
查看更多
登录 后发表回答