Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เมตาอักขระ \t ในนิพจน์ปกติ Java

ซับนิพจน์/เมตาอักขระ “\t” จับคู่ช่องว่างแท็บ (tab spaces)

ตัวอย่างที่ 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("Enter a string: "); 
        String input = sc.nextLine(); 
        Pattern p = Pattern.compile(regex); 
        Matcher m = p.matcher(input); 
        int count = 0; 
        while(m.find()) { 
            count++; 
        } 
        System.out.println("Number of tab spaces: " + count); 
    } 
}

ผลลัพธ์

Enter a string: This      is      a      sentence      with      tab      spaces 
Number of tab spaces: 6

ตัวอย่างที่ 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("Enter a string: "); 
        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("Result: " + result); 
    } 
}

ผลลัพธ์

Enter a string: This is a sentence with tab spaces 
Result: This is a sentence with tab spaces