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

Metaký tự \S trong Regular Expression Java

Phần biểu thức/metaký tự “\S” khớp với các ký tự không phải khoảng trắng (non-white space characters).

Ví dụ 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("Số lần khớp: " + count);
    }
}

Kết quả

Số lần khớp: 38

Ví dụ 2

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

public class Example {
    public static void main(String args[]) {
        String regex = "\\S";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập 5 chuỗi đầu vào: ");
        String input[] = new String[5];
        for (int i = 0; i < 5; i++) {
            input[i] = sc.nextLine();
        }
        // Tạo đối tượng Pattern
        Pattern p = Pattern.compile(regex);
        System.out.println("Số ký tự trong mỗi chuỗi không tính space: ");
        for (int i = 0; i < 5; i++) {
            // Tạo đối tượng Matcher
            Matcher m = p.matcher(input[i]);
            int count = 0;
            while (m.find()) {
                count++;
            }
            System.out.println("Chuỗi " + i + ": " + count);
        }
    }
}

Kết quả

Nhập 5 chuỗi đầu vào: sample123 test data test *123 ab bc cd de hello how are you welcome to Tutorialspoint
Số ký tự trong mỗi chuỗi không tính space:
Chuỗi 0: 9
Chuỗi 1: 8
Chuỗi 2: 8
Chuỗi 3: 8
Chuỗi 4: 37