Java 拆分字符串以获取单词分隔符

Java 拆分字符串以获取单词分隔符,java,regex,Java,Regex,我想找到一个句子中单词之间的所有分隔符,可以是空格,换行符 假设我有以下字符串: String text = "hello, darkness my old friend.\nI've come to you again\r\nasd\n 123123"; String[] separators = text.split("\\S+"); 输出:[, , , , , , , ] 所以我对任何东西进行分割,除了一个空格,它首先返回一个空的分隔符,其余的都很好。为什么一开

我想找到一个句子中单词之间的所有分隔符,可以是空格,换行符

假设我有以下字符串:

String text = "hello, darkness   my old friend.\nI've   come to you again\r\nasd\n 123123";

String[] separators = text.split("\\S+");
输出:
[,
,    ,  ,  ,  , 
, 
]

所以我对任何东西进行分割,除了一个空格,它首先返回一个空的分隔符,其余的都很好。为什么一开始是空字符串

另外,我想在句号和逗号上进行拆分。但是我不知道怎么做,这意味着
“\n”
是一个分隔符

需要上述字符串的输出:

 separators = {", ", "   ", " ", " ", ".\n", "   ", " ", " ", " ", "\r\n", "\n "}


我认为这也可以正常工作:

String[]分隔符=text.split(\\w+)

尝试以下操作:

String[] separators = text.split("[\\w']+");
这将非分隔符定义为“单词字符”和/或撇号

这会在结果数组中留下前导空格,这是无法避免的,除非先删除前导字:

String[] separators = text.replaceAll("^[\\w']+", "").split("[\\w']+");

你可以考虑把连字符加到字符类中,如果你把连字符(前一个句子中的例子)看成一个词,即

String[] separators = text.split("[\\w'-]+");

如果您认为使用
.find()
方法获得所需结果更容易,请参阅。

String text = "hello, darkness   my old friend.\nI've   come to you again\r\nasd\n 123123";

String pat = "[\\s,.]+"; // add all that you need to the character class
Matcher m = Pattern.compile(pat).matcher(text);

List<String> list = new ArrayList<String>();

while( m.find() ) {
    list.add(m.group());
}

// the result is already stored in "list" but if you
// absolutely want to store the result in an array, just do:

String[] result = list.toArray(new String[0]); 
String text=“你好,我的老朋友。\r\n我又来找你了\r\nasd\n 123123”;
字符串pat=“[\\s,.]+”;//将所有需要的内容添加到角色类中
Matcher m=Pattern.compile(pat).Matcher(text);
列表=新的ArrayList();
while(m.find()){
list.add(m.group());
}
//结果已存储在“列表”中,但如果
//要将结果存储在数组中,只需执行以下操作:
String[]result=list.toArray(新字符串[0]);

这样可以避免开始时出现空字符串问题。

对于点和换行符,您需要对其进行转义,例如,
\\.
\\n
您可以尝试使用。的可能重复。就为了你的第一个问题,但你就来了,这是一个一次只问一个问题的完美理由。
String text = "hello, darkness   my old friend.\nI've   come to you again\r\nasd\n 123123";

String pat = "[\\s,.]+"; // add all that you need to the character class
Matcher m = Pattern.compile(pat).matcher(text);

List<String> list = new ArrayList<String>();

while( m.find() ) {
    list.add(m.group());
}

// the result is already stored in "list" but if you
// absolutely want to store the result in an array, just do:

String[] result = list.toArray(new String[0]);