開始使用免費開始

字元比對

你的銷售資料有時會出現錯字或格式錯誤,可能會讓分析失真。在計算總營收之前,你需要先確認所有銷售數量只包含有效的數字字元與小數點。你已從電玩遊戲資料集中擷取了一些銷售數量(單位:百萬)。

本練習屬於課程

使用 Java 進行資料清理

檢視課程

練習說明

  • 檢查 quantity 是否包含任何數字(0 到 9)。
  • quantity 中尋找小數點分隔符。
  • 偵測 quantity 中是否有任何英文字母(小寫或大寫)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class PatternValidation {
    public static void main(String[] args) {
        List quantities = Arrays.asList("41.49", "29.08", "15.85", "12.5x");

        for (String quantity : quantities) {
            // Check if quantity contains any digits
            boolean hasDigits = ____.____('0', '9').matchesAnyOf(quantity);
            // Look for decimal separator in quantity
            boolean hasDecimal = CharMatcher.is('.').____(quantity);
            // Detect any alphabetic characters in quantity
            boolean hasInvalidChars = CharMatcher.inRange('____', '____')
                    .or(CharMatcher.inRange('____', '____')).matchesAnyOf(quantity);

            boolean isValid = hasDigits && hasDecimal && !hasInvalidChars;
            System.out.println(quantity + " has valid characters: " + isValid);
        }
    }
}
編輯並執行程式碼