2016-11-22 98 views
0

我正在寫一個正則表達式模式,它通過HTML標籤進行過濾並僅打印有效標籤的內容以供練習。雖然模式本身似乎正確匹配標籤,但我在打印時遇到了問題。如果聲明過濾掉換行符而不過濾新行。

import java.io.*; 
import java.util.*; 
import java.text.*; 
import java.math.*; 
import java.util.regex.*; 

public class HTMLPattern{ 
    public static void main(String[] args){ 

     Scanner in = new Scanner(System.in); 
     int testCases = Integer.parseInt(in.nextLine()); 

     while(testCases>0){ 
      String line = in.nextLine(); 
      String tagPattern = "<([^>]+)>([^<]*?)</\\1>"; 
      Pattern p = Pattern.compile(tagPattern, Pattern.MULTILINE); 
      Matcher m = p.matcher(line); 
      if(m.find()){ 
       //checks if the output equals a newline 
       if(m.group(2).matches("[\\n\\r]+")){ 
        System.out.println("None");  
       }else{ 
        System.out.println(m.group(2)); 
       } 
      }else{ 
       System.out.println("None"); 
      } 
     testCases--; 
     } 
    } 
} 

當輸入:

3 
<a>test</a> 
<b></b> 
<c>test</c> 

我的輸出應該是:

test 
None 
test 

,而不是是:

test 

test 

我的問題是:爲什麼我的if語句沒有捕捉換行符並打印「無」?

+0

我不是'看到一個新行字符'。你應該測試空節點值,如果你想打印你正在尋找的輸出 – usha

+0

@Vimsha Hmm。我認爲這是一個換行符,因爲我之前檢查空值的所有嘗試都失敗了。 – user2533660

+0

@Vimsha Nvm,我剛剛發現,我會在第二時間回答我的問題。 – user2533660

回答

2

沒有新的生產線,也只是空字符串,嘗試匹配這樣的空字符串:

if (m.group(2).matches("^$")) { 

或檢查字符串的length

if (m.group(2).length() == 0) { 
0

原來沒有換行(s)出現在if語句中。雖然我以前檢查if(m.group(2) == null)嘗試失敗後,.isEmpty()方法正確匹配的空值我是來進行測試:

if(m.find()){ 
    if(m.group(2).isEmpty()){ 
     System.out.println("None");  
     }else{ 
     System.out.println(m.group(2)); 
     } 
    }else{ 
     System.out.println("None"); 
    }