2010-10-15 26 views
1

我有大字符串,它可以有幾千行。我想要列出所有子字符串:[tag] here can be everything [/tag]子串列表

我該怎麼做?我的正則表達式不起作用(或者我做錯了什麼)。

+3

給你做了什麼。 – Wok 2010-10-15 18:08:20

+0

它有特定的格式嗎?從這個問題來看,它看起來有點像BBCode。 – 2010-10-15 18:08:38

+0

您能否將'[]'轉換爲'<>'並使用一些XML解析器? – 2010-10-15 18:31:30

回答

0

find_all_tags返回標籤tag出現的所有的text列表功能:

import re 
def find_all_tags(text, tag): 
    return re.findall(r"(?s)\[" + tag + r"\].*?\[/" + tag + r"\]", text) 

>>> text="""this is [b]bold text[/b] and some[b] 
that spans a line[/b] some [i]italics[/i] and some 
[b][i]bold italics[/i][/b]""" 
>>> find_all_tags(text, "b") 
['[b]bold text[/b]', '[b]\nthat spans a line[/b]', '[b][i]bold italics[/i][/b]'] 

告訴我,如果你需要不同的東西(如發電機,而不是字符串的列表)

+0

我想知道我的答案如何被判斷爲「沒有用」,並且值得讚揚; AFAIU,正是這個問題所要求的。 – tzot 2010-10-16 14:46:15

0

你可以只使用字符串分割

for item in my_big_string.split("]"): 
    if "[" in item: 
     print item.split("[")[-1] 

>>> text="""this is [b]bold text[/b] and some[b] 
... that spans a line[/b] some [i]italics[/i] and some 
... [b][i]bold italics[/i][/b]""" 

>>> for item in text.split("]"): 
... if "[" in item: 
...  print item.split("[")[-1], 
... 
b /b b /b i /i b i /i /b 
>>>