Java正則表達式匹配回車換行多行

默認情況下.*中的.只能匹配出\n以外的字符,如果遇到要匹配的字符串包含回車換行符(多行),則正則表達式遇到換行符後會停止,導致包含回車換行符的串不能正確匹配,解決的辦法是:
1、使用Pattern和Matcher對象
設置Pattern模式爲:Pattern.DOTALL
2、使用String.replaceAll()
正則表達式寫法:
String reg = "(?s)'.*'";

下面是一個包含回車換行字符的正則表達式替換處理例子。


	static String teststr = "UAPPROJECT_ID='402894cb4833decf014833e04fd70002 ; \n\r */' select ";
			
	/**
	 * 包含回車換行符的處理
	 */
	public void testa(){
		Pattern wp = Pattern.compile("'.*?'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); 
		Matcher m = wp.matcher(teststr);
		String result = m.replaceAll("");
		System.out.println("result:" + result);		
	}
	
	/**
	 * 包含回車換行符的處理
	 */
	public void testb(){
		String result = teststr.replaceAll("(?s)'.*?'", "");		
		System.out.println("result:" + result);	
	}	
	


發佈了109 篇原創文章 · 獲贊 17 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章