如何根据某些字符在Java中拆分字符串?

时间:2016-12-09 23:22:10

标签: java split

我分裂了

String example = "That's called -- a cross-country vehicle!";

进入数组:

[That's, called, a, cross-country, vehicle]

使用String.split()

到目前为止,我已尝试使用example.split(" "); 并使用for循环打印出来,我得到了:

That's, called, --, a, cross-country, vehicle!.

但是,我希望它忽略--!。我想只打印出通过单词连接器连接的单词和单词。

1 个答案:

答案 0 :(得分:0)

你想分开一个空格或爆炸,加上可选的更多破折号和空格紧跟在下面:

example.split("[! ][- ]*");

请参阅live demo

String example = "That's called -- a cross-country vehicle!";
String[] words = example.split("[! ][- ]*");
System.out.println(Arrays.toString(words));

输出:

[That's, called, a, cross-country, vehicle]