Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我一直在使用myString.split("\\s+");来获取每个单词。但现在我也想拆分逗号和句号。例如:
myString.split("\\s+");
妈妈总是说生活就像一盒巧克力,你永远不知道你会得到什么。
到:
{Mama, always, said, life, was, like, a, box, of, chocolates ,,, You, never, know, what, you're, gonna, get,.,}
怎么做呢?
如果逗号和句点后面总是跟着空格或字符串结尾,那么你可以这样写:
myString.split("(?=[,.])|\\s+");
如果它们不是并且您希望例如a,b被分成三个字符串,那么:
a,b
myString.split("(?<=[,.])|(?=[,.])|\\s+");
您也可以在点和逗号之前使用前瞻来拆分:
myString.split("\\s+|(?=[,.])");
前瞻不包含在实际匹配中,因此实际字符(逗号或句点)将最终出现在结果数组中。