2017-03-22 46 views
1

我有一個字符串,我想分割在特定的段,但我不能匹配正確的段的字符串,因爲兩個相同的模式發生。使用正則表達式查找特定的段

我的字符串:

@if(text.text isempty){<customer_comment>@cc{txt_without_comments}[email protected]</customer_comment>}else{@if(text.answer=='no'){<customer_comment>@{text.text}</customer_comment>}else{<answer>@{text.text}</answer>}[email protected]}[email protected] 

我需要匹配:@if(text.text的isEmpty){@ CC {} txt_without_comments CC @}其他{....} ENDIF @

和而不是else塊中的嵌套點。

這裏是我的不完整的正則表達式:

(?<match>(?<open>@if\((?<statement>[^)]*)\)\s*{)(?<ifblock>(.+?)(?:}else{)(?<elseblock>.*))(?<-open>)}[email protected]) 

這正則表達式是ifblock組也應該停止在第一}其他{圖案太貪婪。

編輯: 這是確切的結果,我想製作:

match: @if(text.text isempty){<customer_comment>@cc{txt_without_comments}[email protected]</customer_comment>}else{@if(text.answer=='no'){<customer_comment>@{text.text}</customer_comment>}else{<answer>@{text.text}</answer>}[email protected]}[email protected] 

statement: text.text isempty 

ifblock: <customer_comment>@cc{txt_without_comments}[email protected]</customer_comment> 

elseblock: @if(text.answer=='no'){<customer_comment>@{text.text}</customer_comment>}else{<answer>@{text.text}</answer>}[email protected] 
+0

請提供確切的預期結果。 –

+1

我想要的結果發佈到問題。 –

回答

1

你沒有正確使用balancing groups。平衡組必須用於通過捕獲將一些值推入堆棧,並使用其他捕獲將其從堆棧中移除,然後需要conditional construct來檢查組堆棧是否爲空,如果不是,則無法使匹配執行回溯。

所以,如果正則表達式是爲你匹配這些字符串的唯一途徑,使用以下命令:

(?s)(?<match>@if\((?<statement>[^)]*)\)\s*{\s*(?<ifblock>.*?)\s*}\s*else\s*{\s*(?<elseblock>@if\s*\((?:([email protected]\s*\(|\}\s*[email protected]).|(?<a>)@if\s*\(|(?<-a>)\}\s*[email protected])*(?(a)(?!)))\}\s*[email protected]) 

regex demo。但是,編寫自定義分析器可能會在此處找到更好的方法。

圖案的詳細資料

  • (?s) - 上單線模式(.匹配換行)
  • (?<match> - 一個文字字符序列@if(
  • - 外組 「匹配」
  • @if\(的開始
  • (?<statement>[^)]*) - 羣組「語句」捕獲除)之外的0+個字符
  • \)\s*{\s* - ),0 +空格,{,0 +空格
  • (?<ifblock>.*?) - 組 「ifblock」,捕捉任何字符0+,儘可能少到第一...
  • \s*}\s*else\s*{\s* - 0+空格,},0 +空格,else,0 +空格,{,0 +空格
  • (?<elseblock>@if\s*\((?:([email protected]\s*\(|\}\s*[email protected]).|(?<a>)@if\s*\(|(?<-a>)\}\s*[email protected])*(?(a)(?!))) - 組 「elseblock」 捕獲:
    • @if\s*\( - @if,0 +空格, (
    • (?: - 交替組的開始,即重複0+倍
    • )*除去 - 交替組的端
    • (?(a)(?!)) - 如果ifendif平衡量是匹配的
  • \}\s*[email protected]條件檢查 - },0+空格,[email protected]
  • ) - 外 「匹配」 組的端部。