Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách khớp khoảng trắng dùng Java RegEx

Metaký tự "\\s" khớp các ký tự khoảng trắng trong chuỗi cho trước.

Ví dụ 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String args[]) {
        // Đọc chuỗi từ người dùng
        System.out.println("Nhập một chuỗi");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String regex = "\\s";
        
        // Biên dịch biểu thức chính quy
        Pattern pattern = Pattern.compile(regex);
        
        // Lấy đối tượng matcher
        Matcher matcher = pattern.matcher(input);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        System.out.println("Số khoảng trắng: " + count);
    }
}

Kết quả

Nhập một chuỗi Hello how are you welcome to tutorialspoint
Số khoảng trắng: 6

Ví dụ 2

import java.util.Scanner;

public class RegexExample {
    public static void main(String args[]) {
        // Biểu thức chính quy
        String regex = "\\s+";
        System.out.println("Nhập giá trị đầu vào: ");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String result = input.replaceAll(regex, "");
        System.out.println("Kết quả: " + result);
    }
}

Kết quả

Nhập giá trị đầu vào: hello how are you
Kết quả: hellohowareyou