2012-10-30 51 views
0

我爲了變換像正則表達式解析

{test}hello world{/test} and {again}i'm coming back{/again} in hello world i'm coming back. 

我試圖{[^}]+}但這個表達式,我不僅是我在測試和重新標籤有正在尋找一個正則表達式。有沒有辦法來完成這個正則表達式?

+1

正則表達式只匹配模式。它不會更改字符串。你喜歡用什麼語言? –

+0

我正在使用Objective-C。 – seb

回答

1

正確執行此操作通常超出了正則表達式的功能。但是,如果你能保證這些標籤永遠不會被嵌套,並您輸入絕不會包含不意味着標籤大括號,那麼這個正則表達式可以做的匹配:

\{([^}]+)}(.*?)\{/\1} 

說明:

\{  # a literal { 
(  # capture the tag name 
[^}]+) # everything until the end of the tag (you already had this) 
}   # a literal } 
(  # capture the tag's value 
.*?)  # any characters, but as few as possible to complete the match 
      # note that the ? makes the repetition ungreedy, which is important if 
      # you have the same tag twice or more in a string 
\{  # a literal { 
\1  # use the tag's name again (capture no. 1) 
}   # a literal } 

因此,這使用反向引用\1來確保結束標記包含與開始標記相同的單詞。然後,您將在捕獲1中找到該標籤的名稱以及捕獲的標籤值/內容2。從這裏你可以用這些你想做的任何事情(例如,將這些值重新組合)。

請注意,如果您希望標籤跨越多行,則應使用SINGLELINEDOTALL選項。

+0

事實上,我使用這個正則表達式來獲取HTML代碼中的HTML標籤中的< div >和< p >之間的所有文本。我試圖用< and >替換{和},它不起作用。一個主意? – seb

+0

@seb您的標籤是否包含屬性?你使用'SINGLELINE'還是'DOTALL'選項(我不知道如何在Objective C中設置,不好意思)。另外,如果您正在解析HTML,請**使用DOM解析器代替。 –

+0

是的,我的標籤有時包含屬性。 – seb