Java Regular Expression

javadoc中dot的敘述

某天我仔細閱讀javadoc時,發現dot說明為Any character (may or may not match line terminators);我對dot的認知應該是除了跳行以外的任何字元,為此特別查詢一下原因。我認為正常的情況是may not match line terminators:

@Test
public void testPatternWithoutDotAll(){
	Pattern p = Pattern.compile("test.*");
	Matcher m = p.matcher("test 123\n456");
	assertTrue(m.find());
	assertEquals("test 123",  m.group());	
}
但當使用compile攜帶Pattern.DOTALL參數時,就會是may match line terminators:
@Test
public void testPatternWithDotAll(){
	Pattern p = Pattern.compile("test.*4", Pattern.DOTALL);
	Matcher m = p.matcher("test 123\n456");
	assertTrue(m.find());
	assertEquals("test 123\n4",  m.group());	
}

為何square只能用在第一行?

我想找開頭為test的那行,我使用以下的pattern:

@Test
public void testPatternWithSqure(){
	Pattern p = Pattern.compile("^test.*");
	Matcher m = p.matcher("abc\ntest123\n567");
	assertTrue(m.find());
	assertEquals("test123",  m.group());	
}
執行後會test failed,但test在第一行卻會很正常;最後爬文得知,要搭配Pattern.MULTILINE一起使用:
@Test
public void testPatternWithSqure(){
	Pattern p = Pattern.compile("^test.*", Pattern.MULTILINE);
	// 略過
}