2015-08-18 32 views
7

Wikipedia任何頁面:Java的正則表達式如何找到父匹配?

... 
abas asdn asf asfs af 
{{Template1 
|a = Name surname 
|b = jhsdf sdf 
|c = {{Template2}} 
|d = 
|e = [[f]] and [[g]] 
|h = asd asdasfgasgasg asgas jygh trdx dftf xcth 
|i = 73 
|j = {{Template2|abc|123}} 
|j = {{Template3|aa=kkk|bb={{Template4|cc=uu}}}} 
}} 

asd wetd gdsgwew g 

{{OtherTemplate 
|sdf = 213 
}} 
... 

我怎樣才能找到Template1的內容(開始時|a到底是}})與Java正則表達式?

我想:

String pattern = "\\{\\{\\s*Template1\\s*(.*?)\\}\\}"; 

Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); 
Matcher m = p.matcher(content); 

while (m.find()) { 
    if (!m.group().equals("")) { 
     System.out.println(m.group()); 
     System.out.println("-----------------------"); 
    } 
} 

但在這裏的正則表達式是找到第一}}(這是Template2}})然後停止。
我想通過}}是任何{{是開放的。然後我想找到頂級的父母匹配。

我想獲得頂部{{}}之間的頂部Template1

編輯:

請記住去除空格後我解析content

content.replaceAll("\\s+",""); 

將內容視爲編寫單行。

+3

使用'Jsoup' api。比編寫正則表達式更簡單 – TheLostMind

+0

強烈建議不要使用正則表達式來解析標記,或使用分層語法的任何東西。使用您自己的解析器或任何可用的產品(另請參閱TheLostMind的評論)。 – Mena

+0

@TheLostMind不是jsoup HTML解析器?我如何解析「{{」與「jsoup」 – MarsPeople

回答

1

/^{{Template1(.*?)^}}/sm

回報:

|a = Name surname 
|b = jhsdf sdf 
|c = {{Template2}} 
|d = 
|e = [[f]] and [[g]] 
|h = asd asdasfgasgasg asgas jygh trdx dftf xcth 
|i = 73 
|j = {{Template2|abc|123}} 
|j = {{Template3|aa=kkk|bb={{Template4|cc=uu}}}} 

https://regex101.com/r/qC6cM1/1(DEMO)

+0

當改變行到「| j = {{Template3 | aa = kkk | bb = {{Template4 | cc = uu}}}}}}時,刪除空格不起作用。」 – MarsPeople

+0

我不明白你在說什麼 - 什麼是空白? –

+0

當你移動「模板1」結束標記「}}」結束「| j」行這個正則表達式不起作用。 (空格:當你刪除所有換行符時,使單行全部內容) – MarsPeople

0

我覺得解析器會做的更好JUB在這種情況下,但如果你想正則表達式,怎麼樣這一個:

{{Template1(?:[^{}]*?(?:{{[^}]+?}}))+(?:[}\n\s]+})* 

DEMO

我認爲你輸入的是像單行。

+0

這是不工作時最後}}移動到換行符:喜歡:https://regex101.com/r/eL5fR0/3 – MarsPeople

+0

@Kumul和這一個:[演示](https://regex101.com/r/eL5fR0/4)。它有點改變 –

+0

嘿它看起來不錯。我正在嘗試錯誤。如果它的工作沒有bug,我會接受答案。給我一些時間嘗試。 – MarsPeople