Làm sạch dữ liệu bằng Java
Dennis Lee
Software Engineer
| Product Name | Category | Status | Date Received | Quantity |
|---|---|---|---|---|
| Eggplant | Fruits & Vegetables | Discontinued | 3/1/25 | 46 |
| VEGETABLE OIL | Oils & Fats | Backordered | 4/1/25 | 51 |
| Cheese | Dairy | Active | 6/1/25 | 78 |
| Fresh (Organic) *Carrots* | Fruits & Vegetables | Discontinued | 5/1/25 | 51 |
| Bell Pepper Fresh | Fruits & Vegetables | Active | 5/2/25 | 67 |
String[] messyProducts = {
"Eggplant ", // Dư khoảng trắng cuối
"VEGETABLE OIL", // Không thống nhất chữ hoa/thường
"Fresh (Organic) *Carrots*", // Ký tự đặc biệt
"Bell Pepper Fresh", // Dư khoảng trắng giữa các từ
};
String[] products = {"Eggplant ", " Vegetable Oil", " Cheese "};
for (String product : products) {
String cleaned = product.trim(); // Xóa khoảng trắng đầu/cuối
System.out.println(cleaned);
}
Eggplant
Vegetable Oil
Cheese
List<String> products = Arrays.asList("Eggplant", "VEGETABLE OIL", "cheese");products.stream().map(String::toLowerCase) // Chuyển hết sang chữ thường.forEach(System.out::println); // In từng sản phẩm
eggplant
vegetable oil
cheese
[^a-zA-Z\\s]: Tìm ký tự không phải chữ cái hoặc khoảng trắng// Mẫu này khớp mọi ký tự KHÔNG phải:
[ // Bắt đầu tập ký tự
^ // PHỦ ĐỊNH - khớp mọi thứ không trong tập
a-z // chữ thường
A-Z // chữ hoa
\\s // ký tự khoảng trắng (cần thêm \ để Java hiểu \s)
] // Kết thúc tập ký tự
String dirtyName = "Fresh (Organic) *Carrots*"; // Ký tự đặc biệt: (, ), *String cleaned = dirtyName.replaceAll("[^a-zA-Z\\s]", ""); // Loại bỏ ký tự không phải chữSystem.out.println(cleaned); // Kết quả: "Fresh Organic Carrots"
Fresh Organic Carrots
import java.util.regex.Pattern;
Pattern pattern = Pattern.compile("\\s+"); // Khớp nhiều khoảng trắng liên tiếpString messyProduct = "Bell Pepper Fresh"; // Dư nhiều khoảng trắng // Thay nhiều khoảng trắng bằng một khoảng trắng String cleanedProduct = pattern.matcher(messyProduct).replaceAll(" ");System.out.println(cleanedProduct);
Bell Pepper Fresh
List<String> messyProducts = Arrays.asList(
"Eggplant ", "VEGETABLE OIL",
"Fresh (Organic) *Carrots*", "Bell Pepper Fresh"
); // Tên sản phẩm trích xuất từ bộ dữ liệu tồn kho tạp hóa
messyProducts.stream()
.map(s -> s.trim() // Xóa khoảng trắng đầu/cuối
.replaceAll("[^a-zA-Z\\s]", "") // Bỏ ký tự đặc biệt
.replaceAll("\\s+", " ") // Sửa khoảng trắng thừa
.toLowerCase()) // Chuẩn hóa chữ thường
.forEach(System.out::println);
eggplant
vegetable oil
fresh organic carrots
bell pepper fresh
Làm sạch dữ liệu bằng Java