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

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

Phần biểu thức/metaký tự “\A” khớp với đầu của toàn bộ chuỗi.

Ví dụ 1

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

public class RegexExample {
    public static void main(String args[]) {
        String regex = "\\AHi";
        String input = "Hi 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

Chương trình Java sau chấp nhận chuỗi từ người dùng kiểm tra xem nó có chứa ký tự non-ASCII không.

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

public class StartingOfInput {
    public static void main(String args[]) {
        String regex = "\\A\\p{ASCII}*\\z";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập chuỗi đầu vào: ");
        String input = sc.nextLine();
        
        // Tạo đối tượng Pattern
        Pattern p = Pattern.compile(regex);
        
        // Tạo đối tượng Matcher
        Matcher m = p.matcher(input);
        if (m.find()) {
            System.out.println("Đầu vào chỉ chứa ký tự ASCII");
        } else {
            System.out.println("Đầu vào chứa ký tự non-ASCII");
        }
    }
}

Kết quả 1

Nhập chuỗi đầu vào: What is your name
Đầu vào chỉ chứa ký tự ASCII

Kết quả 2

Nhập chuỗi đầu vào: whÿ do we fall
Đầu vào chứa ký tự non-ASCII