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

Cách xóa khoảng trắng bằng biểu thức chính quy Java (RegEx)


Biểu thức chính quy "\\s" khớp với các khoảng trắng trong chuỗi. Phương thức replaceAll() chấp nhận một chuỗi và một biểu thức chính quy, thay thế các ký tự khớp bằng chuỗi cho trước. Để xóa tất cả khoảng trắng từ chuỗi đầu vào, gọi phương thức replaceAll() trên chuỗi đó với regex "\\s" và chuỗi rỗng "" làm tham số.

Ví dụ 1: Sử dụng replaceAll()

public class RemovingWhiteSpaces {
    public static void main(String args[]) {
        String input = "Hi welcome to tutorialspoint";
        String regex = "\\s";
        String result = input.replaceAll(regex, "");
        System.out.println("Kết quả: " + result);
    }
}

Kết quả

Kết quả: Hiwelcometotutorialspoint

Ví dụ 2: Sử dụng Matcher.appendReplacement()

Tương tự, phương thức appendReplacement() chấp nhận một StringBuffer và chuỗi thay thế, nối các ký tự khớp với chuỗi thay thế và thêm vào StringBuffer.

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

public class RemovingWhiteSpaces {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập chuỗi đầu vào: ");
        String input = sc.nextLine();
        String regex = "\\s";
        String constants = "";
        System.out.println("Chuỗi đầu vào: \n" + input);
        
        // Tạo đối tượng Pattern
        Pattern pattern = Pattern.compile(regex);
        
        // Khớp pattern trong chuỗi
        Matcher matcher = pattern.matcher(input);
        
        // Tạo StringBuffer rỗng
        StringBuffer sb = new StringBuffer();
        
        while (matcher.find()) {
            constants = constants + matcher.group();
            matcher.appendReplacement(sb, "");
        }
        matcher.appendTail(sb);
        System.out.println("Kết quả: \n" + sb.toString() + constants);
    }
}

Kết quả

Nhập chuỗi đầu vào: this is a sample text with white spaces
Chuỗi đầu vào: this is a sample text with white spaces
Kết quả: thisisasampletextwithwhitespaces

Ví dụ 3: Sử dụng split() và nối chuỗi

public class Just {
    public static void main(String args[]) {
        String input = "This is a sample text with spaces";
        String str[] = input.split(" ");
        String result = "";
        for (int i = 0; i < str.length; i++) {
            result = result + str[i];
        }
        System.out.println("Kết quả: " + result);
    }
}

Kết quả

Kết quả: Thisisasampletextwithspaces