Java 将字符串拆分为单词逗号和句号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13615939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Split string into words commas and full stops
提问by Reg
I have been using myString.split("\\s+");
to get the each word. But now I want to split the commas and full stops aswell. For Example:
我一直在使用myString.split("\\s+");
来获取每个单词。但现在我想拆分逗号和句号。例如:
Mama always said life was like a box of chocolates, you never know what you're gonna get.
妈妈总是说生活就像一盒巧克力,你永远不知道会得到什么。
to:
到:
{Mama, always, said, life, was, like, a, box, of, chocolates ,,, You, never, know, what, you're, gonna, get,.,}
How would one go about doing this?
怎么做呢?
回答by ruakh
If commas and periods are always followed by whitespace or end-of-string, then you can write:
如果逗号和句点后面总是跟有空格或字符串结尾,那么你可以这样写:
myString.split("(?=[,.])|\s+");
If they're not and you want e.g. a,b
to be split into three strings, then:
如果它们不是,并且您想a,b
将其拆分为三个字符串,则:
myString.split("(?<=[,.])|(?=[,.])|\s+");