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

Metaký tự \t trong Regular Expression Java

Phần biểu thức/metaký tự “\t” khớp với khoảng cách tab (tab spaces).

Ví dụ 1

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

public class RegexExample {
    public static void main(String args[]) {
        String regex = "\\t";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập một chuỗi: ");
        String input = sc.nextLine();
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        int count = 0;
        while (m.find()) {
            count++;
        }
        System.out.println("Số khoảng tab: " + count);
    }
}

Kết quả

Nhập một chuỗi: This     is     a     sentence     with     tab     spaces
Số khoảng tab: 6

Ví dụ 2

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

public class RegexExample {
    public static void main(String args[]) {
        String regex = "\\t";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập một chuỗi: ");
        String input = sc.nextLine();
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        int count = 0;
        String result = "";
        while (m.find()) {
            result = m.replaceAll(" ");
        }
        System.out.println("Kết quả: " + result);
    }
}

Kết quả

Nhập một chuỗi: This is a sentence with tab spaces
Kết quả: This is a sentence with tab spaces