2014-01-08 33 views
0

我有一個這樣的字符串..正則表達式和自定義標籤

<mytag>one line</mytag><mytag>second line with other tag <color=red>this words are red</color></mytag><youtube>GY7IU5FU</youtube> 

我怎樣才能得到這個..

1 - (TAG) - mytag 
1 - (DATA) - one line 
2 - (TAG) - mytag 
2 - (DATA) - second line with other tag <color=red>this words is red</color> 
3 - (TAG) - youtube 
3 - (DATA) - GY7IU5FU 

林與此嘗試,但不起作用

<(.*).*?<\/?\1> 
+0

使用html解析器 – tenub

+0

爲什麼要使用正則表達式?這是html。 – mikea

+0

或者只是在您的正則表達式中使用捕獲組。快速谷歌搜索'java正則表達式捕獲組'揭示[this](http://www.javamex.com/tutorials/regular_expressions/capturing_groups.shtml#.Us1ymGRDsrg) – tenub

回答

1

從一點經驗說起,正則表達式根本不會被切斷,因爲重載解析是不可能的。 HTML屬於該類別。

您需要一個全面的解析器。幸運的是,SO有你需要的信息here

0

作爲部分回答你的問題可能幫助你開始,這裏是一些Java:

Pattern p = Pattern.compile("<[^<>]*?>"); 
Matcher m = p.matcher("<mytag>foo</mytag>"); 
if (m.find()){ 
    String str= m.group(0) 
} 

這段代碼捕獲<mytag>foo</mytag>mytag。希望這可以幫助。

0

解決方案在Python(重新對正則表達式模塊):

re.findall(r"<(mytag|youtube)>(.*?)</\1>",a) 

Output: 
[('mytag', 'one line'), 
('mytag', 'second line with other tag <color=red>this words are red</color>'), 
('youtube', 'GY7IU5FU')] 

說明:此正則表達式一個mytag或YouTube標籤開始,其次是標籤內的文本(在非貪婪的方式匹配避免的情況下 AB將匹配ab作爲文本

如果你想匹配所有頂級標籤和內容然後用下面的正則表達式的字符串:

<(.+)>(.*?)</\1>