เปิดใช้งานโหมดหลายบรรทัด
โดยทั่วไป อักขระเมตา ^ และ $ จะจับคู่จุดเริ่มต้นและจุดสิ้นสุดของอินพุตที่กำหนดกับอักขระที่ระบุโดยไม่คำนึงถึงจำนวนบรรทัดในนั้น
ตัวอย่างที่ 1
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));
}
}
} ผลลัพธ์
2234
เมื่อคุณใช้ค่านี้เป็นค่าแฟล็กสำหรับวิธีการคอมไพล์ () ลำดับอินพุตทั้งหมดจะถือเป็นบรรทัดเดียว และอักขระเมตา ^ และ $ จะตรงกับจุดเริ่มต้นและจุดสิ้นสุดของลำดับอินพุตที่กำหนด
ตัวอย่างที่ 2
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));
}
}
} ผลลัพธ์
2234 1424