我正在寫一個正則表達式模式,它通過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語句沒有捕捉換行符並打印「無」?
我不是'看到一個新行字符'。你應該測試空節點值,如果你想打印你正在尋找的輸出 – usha
@Vimsha Hmm。我認爲這是一個換行符,因爲我之前檢查空值的所有嘗試都失敗了。 – user2533660
@Vimsha Nvm,我剛剛發現,我會在第二時間回答我的問題。 – user2533660