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

อธิบายเมตาอักขระ \s ในนิพจน์ปกติ Java

ซับนิพจน์/เมตาอักขระ “\s” จับคู่ตัวอักษรช่องว่าง (white space equivalent)

ตัวอย่างที่ 1

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class RegexExample { 
    public static void main( String args[] ) { 
        String regex = "\\s"; 
        String input = "Hello how are you welcome to Tutorialspoint !"; 
        Pattern p = Pattern.compile(regex); 
        Matcher m = p.matcher(input); 
        int count = 0; 
        while(m.find()) { 
            count++; 
        } 
        System.out.println("Number of matches: " + count); 
    } 
}

ผลลัพธ์

Number of matches: 7

ตัวอย่างที่ 2

ตัวอย่างต่อไปนี้อ่านสตริงและลบช่องว่างเพิ่มเติมระหว่างคำ

import java.util.Scanner; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
public class Example { 
    public static void main(String args[]) { 
        // อ่านสตริงจากผู้ใช้ 
        System.out.println("Enter a String"); 
        Scanner sc = new Scanner(System.in); 
        String input = sc.nextLine(); 
        // นิพจน์ปกติจับคู่ช่องว่าง (1 หรือมากกว่า) 
        String regex = "\\s+"; 
        // คอมไพล์นิพจน์ปกติ 
        Pattern pattern = Pattern.compile(regex); 
        // ดึงออบเจ็กต์ matcher 
        Matcher matcher = pattern.matcher(input); 
        // แทนที่ช่องว่างทั้งหมดด้วยช่องว่างเดียว 
        String result = matcher.replaceAll(" "); 
        System.out.print("Text after removing unwanted spaces: \n" + result); 
    } 
}

ผลลัพธ์

Enter a String hello this is a sample text with irregular spaces 
Text after removing unwanted spaces: hello this is a sample text with irregular spaces