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

Biểu thức chính quy (re) Sub-Expression trong Java

Phần biểu thức/metaký tự “( )” nhóm các biểu thức chính quy và ghi nhớ văn bản đã khớp (capturing group).

Ví dụ 1

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

public class Example {
    public static void main(String args[]) {
        String input = "Hello how are you welcome to Tutorialspoint";
        String regex = "H(ell|ow)";
        
        // Biên dịch biểu thức chính quy
        Pattern pattern = Pattern.compile(regex);
        
        // Lấy đối tượng matcher
        Matcher matcher = pattern.matcher(input);
        
        if (matcher.find()) {
            System.out.println("Tìm thấy khớp");
        } else {
            System.out.println("Không tìm thấy khớp");
        }
    }
}

Kết quả

Tìm thấy khớp

Ví dụ 2

Trong ví dụ sau, chúng ta thử khớp một câu có chứa chữ số.

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

public class PatternExample {
    public static void main(String[] args) {
        System.out.println("Nhập chuỗi đầu vào: ");
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        
        // Biểu thức chính quy sử dụng nhóm
        String regex = "(?:.*)(\\d+)(.*)";
        
        // Tạo đối tượng pattern
        Pattern pattern = Pattern.compile(regex);
        
        // Tạo đối tượng Matcher
        Matcher matcher = pattern.matcher(input);
        boolean bool = matcher.matches();
        
        if (bool) {
            System.out.println("Tìm thấy khớp");
        } else {
            System.out.println("Không tìm thấy khớp");
        }
    }
}

Kết quả

Nhập chuỗi đầu vào: This is a 5363 test string
Tìm thấy khớp