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

จับคู่หลายบรรทัดใน Java Regex

เพื่อค้นหา/จับคู่ข้อมูลที่มีหลายบรรทัด ให้ทำตามขั้นตอน:

  1. รับข้อความเข้า (input string)
  2. แยกเป็นอาร์เรย์ токันด้วย split("\r?\n")
  3. คอมไพล์ regex ด้วย Pattern.compile()
  4. สร้าง Matcher ด้วย matcher()
  5. ในลูป for หาจับคู่ในแต่ละบรรทัดด้วย find()
  6. รีเซ็ต Matcher ให้ชี้บรรทัดถัดไปด้วย reset()

ตัวอย่าง: หาตัวเลขในแต่ละบรรทัด

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

public class MatchingText {
    public static void main(String[] args) {
        String input = "sample text line 1 \n line2 353 35 63 \n line 3 53 35";
        String regex = "\\d";
        String[] strArray = input.split("\r?\n");
        
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        
        for (int i = 0; i < strArray.length; i++) {
            matcher.reset(strArray[i]);
            System.out.println("Line:: " + (i + 1));
            while (matcher.find()) {
                System.out.print(matcher.group() + " ");
            }
            System.out.println();
        }
    }
}

ผลลัพธ์

Line:: 1 1
Line:: 2 2 3 5 3 3 5 6 3
Line:: 3 3 5 3 3 5

อธิบาย

  • \r?\n จับคู่ทั้ง Windows (\r\n) และ Unix (\n) line endings
  • matcher.reset(strArray[i]) เปลี่ยน input ของ matcher ให้เป็นบรรทัดที่ i
  • \\d จับคู่ตัวเลข 0-9
  • วิธีนี้เหมาะสำหรับประมวลผลข้อมูลแบบบรรทัดต่อบรรทัด

ทางเลือกอื่น

สามารถใช้ flag Pattern.MULTILINE ร่วมกับ ^ และ $ เพื่อจับคู่ต้น/ท้ายบรรทัดได้เช่นกัน