2010-10-15 24 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 
>>>