简体   繁体   English

使用java将字符串拆分为单词和标点符号

[英]Splitting a string into words and punctuation with java

I'm trying to split a string up into words and punctuation, adding the punctuation to the list produced by the split. 我正在尝试将字符串拆分为单词和标点符号,将标点符号添加到拆分生成的列表中。

For instance: String c = "help, me!" 例如: String c = "help, me!"

I want out the list to look like is: 我希望列表看起来像是:

['help', ',', 'me', '!']

So, I want the string split at whitespace with the punctuation split from the words. 所以,我希望字符串在空格中分割,并且从单词中分割出标点符号。 Do you have ideas how to do it? 你有想法怎么做吗?

You can do it using regex as follows: 您可以使用regex以下操作:

String d = Str.split("\\W+");

Updated answer for your question: 更新了您的问题的答案:

String d = Str.split("\\b");

Try this 尝试这个

String str = "help, me!";
        StringTokenizer st = new StringTokenizer(str, ", !", true);
        while (st.hasMoreElements()) {
            System.out.println(st.nextElement());;
        }

Output: 输出:

help
,
   <- space
me
!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM