如何保存所有令牌?

时间:2015-10-23 16:27:18

标签: java regex split comma

我有一个文字。我将它分成句子和单词。接下来我必须将它拆分为令牌(,.?!,...)我在这里遇到了麻烦。你能告诉我哪个正则表达式选择了吗?

这是我的代码,它将文本分成句子和单词。

String s = ReadFromFile();
String sentences[] = s.split("[.!?]\\s*");
String words[][] = new String[sentences.length][]; 
for (int i = 0; i < sentences.length; ++i)
{
    words[i] = sentences[i].split("[\\p{Punct}\\s]+");
}
System.out.println(Arrays.deepToString(words));

所以,我有一个separete数组的句子和一系列单词。但是有了令牌,我有一个问题。

输入数据

  

算术运算符在数学表达式中的使用方式与它们在代数中的使用方式相同。下表列出了算术运算符:   假设整数变量A保持10,变量B保持20,则:

预期结果

  

。 :,:

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是不使用split,它要求您描述您不想要的结果,而是使用Matcher#find并描述您想要查找的内容。

String s = "Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Assume integer variable A holds 10 and variable B holds 20, then:";

Pattern p = Pattern.compile("\\p{Punct}");
       //or Pattern.compile("[.]{3}|\\p{Punct}"); if you want to find "..."
Matcher m = p.matcher(s);
while (m.find()) {
    System.out.println(m.group());
}

输出:

.
:
,
:

您可以将其存储在像List这样的集合中,而不是打印m.group()