2016-03-29 44 views
1

內我有以下的格式的大字符串:的Python:提取所有的子串在標籤之間串

'324/;.ke5 efwef dwe,werwrf <>i want this<> ergy;'56\45,> thu ;lokr<>i want this<> htur ;''\> htur> jur' 

我知道我可以做線沿線的東西:

result= text.partition('<>')[-1].rpartition('<>')[0] 

但是這隻會給我第一個<>和最後一個<>之間的字符串,我怎樣才能遍歷整個字符串並提取每個對應的標記對之間的內容?

回答

1

您可以使用正則表達式和findall()

>>> import re 
>>> s = "324/;.ke5 efwef dwe,werwrf <>i want this<> ergy;'56\45,> thu ;lokr<>i want this<> htur ;''\> htur> jur" 
>>> re.findall(r"<>(.*?)<>", s) 
['i want this', 'i want this'] 

其中(.*?)是將任意次數匹配任何字符在non-greedy模式捕獲組。

+0

嗨,我厭倦了使用你的方法,它起初工作,但後來我試圖用它找到'\/\ /'標籤內的一切,我停止工作,你知道這是爲什麼嗎? @alecxe –

+0

@abcla我認爲這可以並應該作爲一個單獨的問題。如果您需要幫助,請考慮發佈 - 確保提供所有詳細信息。要關閉此主題,請考慮接受答案,謝謝。 – alecxe

0

我覺得string.split()是你想要什麼:

>>> text = """'324/;.ke5 efwef dwe,werwrf <>i want this<> ergy;'56\45,> thu ;lokr<>i want this<> htur ;''\> htur> jur'""" 
>>> print text.split('<>')[1:-1] 
['i want this', " ergy;'56%,> thu ;lokr", 'i want this'] 

split()方法,讓你在參數用作分隔符的字符串列表。 (https://docs.python.org/2/library/string.html#string.split)Then,[1:-1]爲您提供了一個沒有第一個和最後一個元素的列表。

相關問題