我正在编写一个程序来计算文本文件中有效英语单词的总数。在此代码中,我想忽略包含数字或特殊字符的单词,例如“word123”、“123word”、“word&&”、“$name”。目前我的程序检测以数字开头的单词,例如“123number”。但是无法检测到“number123”。谁能告诉我应该如何前进?下面是我的代码:
public int wordCounter(String filePath) throws FileNotFoundException{
File f = new File(filePath);
Scanner scanner = new Scanner(f);
int nonWord = 0;
int count = 0;
String regex = "[a-zA-Z].*";
while(scanner.hasNext()){
String word = scanner.next();
if(word.matches(regex)){
count++;
}
else{
nonWord++;
}
}
return count;
}
最佳答案
失去点:
String regex = "[a-zA-Z]*"; // more correctly "[a-zA-Z]+", but both will work here
点表示“任何字符”,但您需要一个表示“仅由字母组成”的正则表达式。
顺便说一句,您还可以使用 POSIX 表达式更简洁地表达这一点(尽管可能可读性较差):
String regex = "\\p{L}+";
正则表达式 \p{L}
表示“任何字母”。
扩展表达式以包含撇号,撇号可以出现在开头(例如 'tis
)、中间(例如 can't
)或结尾(例如 )耶稣的
,但不超过一次:
String regex = "(?!([^']*'){2})['\\p{L}]+";
关于java - 检查单词是否包含数字或特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34427050/