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

Giải thích Metaký tự \w trong Regular Expression Java

Phần biểu thức/metaký tự “\w” khớp với các ký tự từ (word characters), tức là a-z, A-Z và 0-9.

Ví dụ 1

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

public class RegexExample {
    public static void main(String args[]) {
        String regex = "\\w to";
        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: 1

Ví dụ 2

Ví dụ sau đọc 5 giá trị chuỗi và in ra những chuỗi chứa ký tự từ.

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

public class MatchWordCharacters {
    public static void main(String args[]) {
        String regex = "\\w.*$";
        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("Các chuỗi chứa ký tự từ: ");
        for (int i = 0; i < 5; i++) {
            // Tạo đối tượng Matcher
            Matcher m = p.matcher(input[i]);
            if (m.matches()) {
                System.out.println(m.group());
            }
        }
    }
}

Kết quả

Nhập 5 chuỗi đầu vào: sample test test23 hello## #$%&&
Các chuỗi chứa ký tự từ: sample test test23 hello##