在java中通过标点符号和空格等通过正则表达式拆分字符串

2022-09-01 11:55:57

我有这个文本文件,我读入Java应用程序,然后逐行计算其中的单词。现在,我正在将行拆分为单词

String.split([\\p{Punct}\\s+])"

但我知道我错过了文本文件中的一些单词。例如,“不能”一词应分为“可以”和“t”两个词。

逗号和其他标点符号应完全忽略,并被视为空格。我一直在努力了解如何形成一个更精确的正则表达式来做到这一点,但是当涉及到这一点时,我是一个新手,所以我需要一些帮助。

对于我所描述的目的,什么可能是更好的正则表达式?


答案 1

您的正则表达式中有一个小错误。试试这个:

String[] Res = Text.split("[\\p{Punct}\\s]+");

[\\p{Punct}\\s]+将字符类内部的窗体移动到外部。其他明智的做法是,你也在 a 上拆分,不要在一行中组合拆分字符。++

所以我得到了这个代码

String Text = "But I know. For example, the word \"can\'t\" should";

String[] Res = Text.split("[\\p{Punct}\\s]+");
System.out.println(Res.length);
for (String s:Res){
    System.out.println(s);
}

此结果

10

我知道

例如

这个词

不能

应该

这应该符合您的要求。

作为替代方案,您可以使用

String[] Res = Text.split("\\P{L}+");

\\P{L}means 不是具有属性“Letter”的 unicode 代码点


答案 2

有一个非单词文字,请参阅模式\W

String line = "Hello! this is a line. It can't be hard to split into \"words\", can it?";
String[] words = line.split("\\W+");
for (String word : words) System.out.println(word);

Hello
this
is
a
line
It
can
t
be
hard
to
split
into
words
can
it