我正在尝试使用Scanner从用户输入读取文本文件,并使用特定情况下进行单词分隔符的分隔。其中一个情况是当单词在开头或结尾具有撇号时必须进行分隔,但不应影响单词内的撇号。例如:如果scanner看到像“'tis”这样的单词,则scanner.useDelimiter()应该能够去掉撇号并保留单词“tis”,但是如果它看到像“don't”这样的单词,则应该将单词保留为原样。
我正在使用正则表达式来覆盖分隔符应按其进行分隔的多个情况。正则表达式正在做我需要的事情,但由于某种原因,我的结果在具有空格和单词前面的撇号的单词之前会打印出额外的空格。我对正则表达式不熟悉,不知道如何解决这个问题,但是非常感谢任何建议。
以下是我的文本文件中的单词:
'Twas the night before christmas! But don't open your presents. 'Tis the only way to celebrate.
代码:
我正在使用正则表达式来覆盖分隔符应按其进行分隔的多个情况。正则表达式正在做我需要的事情,但由于某种原因,我的结果在具有空格和单词前面的撇号的单词之前会打印出额外的空格。我对正则表达式不熟悉,不知道如何解决这个问题,但是非常感谢任何建议。
以下是我的文本文件中的单词:
'Twas the night before christmas! But don't open your presents. 'Tis the only way to celebrate.
代码:
public static void main (String[] args){
Pattern p = Pattern.compile("[\\p{Punct}\\s&&[^']]+|('(?![\\w]))+|((?<![\\w])')+");
System.out.println("Please enter a text file name.");
Scanner sc = new Scanner(System.in);
File file = new File(sc.nextLine());
Scanner nSc = new Scanner(file);
nSc.useDelimiter(p);
while (nSc.hasNext()){
String word = nSc.next().toLowerCase();
System.out.println(word);
}
nSc.close();
}
期望值:
twas
the
night
before
christmas
but
don't
open
your
presents
tis
the
only
way
to
celebrate
实际:
twas
the
night
before
christmas
but
don't
open
your
presents
tis
the
only
way
to
celebrate