2011-09-02 52 views
1

我有以下字符串,我想提取元素(xx =「yy」)以及括號之間的內容。這裏有一個例子:提取內部和括號內的元素

[說明ID = 「拿到這本」 ALIGN = 「和這個」 寬度= 「和這個」 標題= 「和 這個」]這也請[/字幕]

我試過下面的代碼,但我很喜歡正則表達式。

re.sub(r'\[caption id="(.*)" align="(.*)" width="(.*)" caption="(.*)"\](.*)\[\/caption\]', "tokens: %1 %2 %3 %4 %5", self.content, re.IGNORECASE) 

非常感謝!

回答

3

它可能不適合你,因爲.*是貪婪的。嘗試使用[^"]*替代。 [^"]表示除引號字符以外的所有字符的集合。另外,正如您在註釋中指出的那樣,令牌語法是\\n,而不是%n。試試這個:

re.sub(r'\[caption id="([^"]*)" align="([^"]*)" width="([^"]*)" caption="([^"]*)"\](.*)\[\/caption\]', "tokens: \\1 \\2 \\3 \\4 \\5", self.content, re.IGNORECASE) 

標題標籤的內容是否跨越多行?如果他們這樣做.*將不會捕獲換行符。您需要給我們一些東西,如[^\x00]*[^\x00]表示除空字符以外的所有charchters的集合。

re.sub(r'\[caption id="([^"]*)" align="([^"]*)" width="([^"]*)" caption="([^"]*)"\]([^\x00]*)\[\/caption\]', "tokens: \\1 \\2 \\3 \\4 \\5", self.content, re.IGNORECASE) 

上關的機會,你的字符串實際上可以合法地包含空字符,你就需要使用re.DOTALL標誌來代替。

+0

根據您的編程語言,您可以將NONGREEDY修飾符添加到表達式。 –

+2

不錯,那個工作!我也忘記了令牌語法是// not%,然後它工作:re.sub(r'\ [caption id =「([^」] *)「align =」([^「] *)」width = 「([^」] *)「caption =」([^「] *)」\](。*)\ [\/caption \]',「tokens:\\ 1 \\ 2 \\ 3 \\ 4 \\ 5「,self.content,re.IGNORECASE) – Clash

+0

@Clash:我已經更新了我的答案,以包含有關令牌語法的部分。 – Asaph

0

你可以嘗試這樣的事情?

re = '[caption id="get this" align="and this" width="and this" caption="and this"]this too please[/caption]' 
re.gsub(/([a-z]*)=\"(.*?)\"/i) do |m| 
    puts "#{$1} = #{$2} 
end 
+1

這是什麼語言? – glglgl

2

你也許能夠利用Python的標準SGML/HTML/XML解析模塊電源:如果它是安全的替代「[]」爲「<>」,那麼你可以爲了做這個替代產生有效的XML,並做標準庫XML解析函數解析:

import string 
from xml.etree import ElementTree as ET 

text = '[caption id="get this" align="and this" width="and this" caption="and this"]this too please[/caption]' 
xml_text = string.translate(text, string.maketrans('[]', '<>')) # Conversion to XML 
parsed_text = ET.fromstring(xml_text) # Parsing 

# Extracted information 
print "Text part:", parsed_text.text 
print "Values:", parsed_text.attrib.values() 

這正確打印:

Text part: this too please 
Values: ['and this', 'and this', 'get this', 'and this'] 

這種方法的好處是, (1)它使用了許多人都知道的標準模塊; (2)明確表明你想要做什麼; (3)您可以隨時提取更多信息,處理更復雜的值(包括包含雙引號的值...)等。