Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Pattern MULTILINE Field ใน Java พร้อมตัวอย่าง


เปิดใช้งาน multiline mode

โดยทั่วไป meta characters ^ และ $ จับคู่จุดเริ่มต้นและจุดสิ้นสุดของอินพุตที่กำหนดกับตัวอักษรที่ระบุ โดยไม่คำนึงถึงจำนวนบรรทัด

ตัวอย่างที่ 1: ไม่ใช้ MULTILINE

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

public class MULTILINE_Example {
    public static void main(String args[]) {
        // String regex = "(^This)";//.*t$)"
        String input = "2234 This is a sample text\n" + "1424 This second 2335 line\n" + "This id third 455 line\n" + "Welcome to Tutorialspoint\n";
        Pattern pattern = Pattern.compile("^([0-9]+).*");//, Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

Output

2234

เมื่อคุณใช้เป็น flag value ในเมธอด compile() ทั้งลำดับอินพุตจะถูกจัดการเป็นบรรทัดเดียว และ meta characters ^ และ $ จะจับคู่จุดเริ่มต้นและจุดสิ้นสุดของลำดับอินพุตที่กำหนด

ตัวอย่างที่ 2: ใช้ MULTILINE

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

public class MULTILINE_Example {
    public static void main(String args[]) {
        // String regex = "(^This)";//.*t$)"
        String input = "2234 This is a sample text\n" + "1424 This second 2335 line\n" + "This id third 455 line\n" + "Welcome to Tutorialspoint\n";
        Pattern pattern = Pattern.compile("^([0-9]+).*", Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

Output

2234
1424