Java 按空格、新行、制表符、标点符号拆分字符串

2022-09-03 03:36:54

每个人 都。

我有一个这样的字符串

String message = "This is the new message or something like that, OK";

我想把它分成数组

String[] dic = {"this", "is", "the", "new", "message", "or", "something", "like", "that", "OK"};

我用过

message = message.split("\\s+");

问题在于它包含“那个”,而不是我想要的“那个”。请教我如何解决它。谢谢


答案 1

你可以做

String[] dic = message.split("\\W+");

表示不是字母数字字符。\\W


答案 2

您可以使用 StringTokenizer

 String message = "This is the new message or something like that, OK";
 String delim = " \n\r\t,.;"; //insert here all delimitators
 StringTokenizer st = new StringTokenizer(message,delim);
 while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
 }