2012-05-22 23 views
0

相關: https://stackoverflow.com/a/2910549/194031C#正則表達式 - 斯普利特和保持分配器

我有這樣的字符串:

"abc defgh <!inc(C:\my files\abc.txt)!>kdi kdkd<!inc(C:\my files\abc.txt)!>" 

,我想:

["abc defgh ", "C:\my files\abc.txt", "kdi kdkd", "C:\my files\abc.txt"] 

而且,我不想要

"abc <!inc(C:\my files\abc.txt adf" (missing end bracket) 

分裂。

基於相關的問題和其他類似的答案,我需要使用前瞻,但我無法弄清楚如何使用它們,同時完成刪除標籤,而不是在部分標籤丟失時不拆分。

回答

2

這可能會幫助您開始。您可能需要再修改一下。

Regex.Split("...", @"<!inc\((?=.*?\)!>)|(?<=<!inc\(.*?)\)!>"); 

表達打破

<!inc\(
(?=.*?\)!>) // this is the positive lookahead to make sure that the string ')!>` 
       // exists before counting this as a match 
| 
(?<=<!inc\(.*?) // positive look behind to make sure '<!inc(' shows up before 
\)!>   
+0

+1 - 雖然不需要在parens中包裝'。*?'。 – Tomalak

+1

'。*?'沒有被包裹,但它看起來像它 – climbage

+0

你是對的,忘記它。 ;) – Tomalak

2

這是你的正則表達式

<!inc\((?=[^)]+\)!>)|(?<=<!inc\([^)]+)\)!> 

它分裂的(和刪除)每<!inc(當且僅當它有一個匹配)!>(反之亦然)。

+0

感謝Tomalak!這幾乎適用於所有情況,除了當我進入多行輸入時,它不再正確拆分。單線,但是很好。對不起,我之前沒有提及多行,我沒有意識到它可能會影響答案。我也嘗試使用RegexOptions.Multiline,但是這並沒有幫助。 – Chad

+0

@Chad多行或單行*應該*不會影響這個正則表達式,至少我看不出如何。 – Tomalak