簡體   English   中英

檢查單詞是否包含數字或特殊字符

[英]check if word contains a number or special character

我正在編寫一個程序來計算文本文件中有效英語單詞的總數。 在此代碼中,我想忽略包含數字/數字或特殊字符的單詞,例如“ 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或者結束處可以出現,例如Jesus' ,但不能超過一次:

String regex = "(?!([^']*'){2})['\\p{L}]+";

使用正則表達式^ [a-zA-Z-] + $進行單詞匹配。

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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM