在 Java 中为 .split 使用多个分隔符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19967972/
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
Using multiple delimiters for .split in Java
提问by Bottlecaps
Right now my code only separates words by white space, but I also want to separate by '.' and "," too. Here is my current code:
现在我的代码只用空格分隔单词,但我也想用 '.' 分隔。还有“,”。这是我当前的代码:
for (String words : input.split("\s+"))
For example, if the user entered "bread,milk,eggs" or "Um...awkss" It would consider that one word, and I want each word to be it's own word.
例如,如果用户输入“bread,milk,eggs”或“Um...awkss”,它会认为是一个词,我希望每个词都是它自己的词。
And while I'm here, I can't get
当我在这里时,我无法得到
input.isAlpha()
to work either.
要么工作。
采纳答案by Dariusz
You can split using this regex
您可以使用此正则表达式拆分
input.split("\s+|.+|,+")
or simply:
或者干脆:
input.split("[\s.,]+")
Remember that a dot doesn't have to be escaped inside square brackets
请记住,点不必在方括号内转义
回答by Paul Samsotha
Use brackets
使用括号
for (String words : input.split("[\s.,]+"))
Brackets are used when you want any of the characters in the brackets, the +
means the characters can be combined one or more times. to create one single delimiter, i.e. space and period
or comma and space
.
当您想要括号中的任何字符时使用括号,这+
意味着这些字符可以组合一次或多次。创建一个分隔符,即space and period
或comma and space
。
回答by UMESH0492
You can use this
你可以用这个
mySring = "abc==abc++abc==bc++abc";
String[] splitString = myString.split("\W+");
Regular expression \W+ ---> it will split the string based upon non-word character.
正则表达式 \W+ ---> 它将根据非单词字符拆分字符串。