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

Giải thích Quantifiers trong Java Regular Expressions


Bảng Quantifiers

QuantifierMô tảVí dụ
re*0 hoặc nhiều lần[0-9]*: 0 hoặc nhiều chữ số
re?0 hoặc 1 lần[0-9]?: 0 hoặc 1 chữ số
re+1 hoặc nhiều lần[0-9]+: 1 hoặc nhiều chữ số
re{n}Chính xác n lần[0-9]{3}: 3 chữ số
re{n,}Tối thiểu n lần[0-9]{3,}: ít nhất 3 chữ số
re{n,m}Từ n đến m lần[0-9]{2,5}: 2-5 chữ số

Ví dụ: Validate số 3-6 chữ số

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 = "[0-9]{3,6}";
        Scanner sc = new Scanner(System.in);
        System.out.println("Nhập 5 chuỗi: ");
        String[] input = new String[5];
        for (int i = 0; i < 5; i++) {
            input[i] = sc.nextLine();
        }
        Pattern p = Pattern.compile(regex);
        System.out.println("Giá trị khớp: ");
        for (int i = 0; i < 5; i++) {
            Matcher m = p.matcher(input[i]);
            if (m.matches()) {
                System.out.println(m.group() + ": accepted");
            }
        }
    }
}

Kết quả

Nhập 5 chuỗi: 12 154 4587 478365 4578952
Giá trị khớp:
154: accepted
4587: accepted
478365: accepted

Lưu ý

  • matches() yêu cầu toàn bộ chuỗi khớp regex. Dùng find() để tìm substring khớp.
  • Quantifiers mặc định là greedy. Thêm ? thành reluctant, + thành possessive.
  • {n,} không có khoảng trắng sau dấu phẩy: {3,} đúng, {3, } sai.