2010-01-27 78 views

回答

2

如果不能嵌套的標籤,你可以使用下面的正則表達式:

\[%=(.*?)%] 

的符號的含義如下:

 
\[ Match a literal [ character. The backslash is required otherwise [ would 
     start a character class. 
%= Match %= 
(.*?) Match any characters, non-greedy. i.e. as few as possible. The parentheses 
     capture the match so that you can refer to it later. 
%] Match %] - Note that it is not necessary to escape ] here, but you can if 
     you want. 

這裏是你如何在C#中使用它:

string s = "sanfdsg[%=jdgashg%]jagsklasg"; 
Match match = Regex.Match(s, @"\[%=(.*?)%]"); 
if (match.Success) 
{ 
    Console.WriteLine(match.Groups[1].Value); 
} 

輸出:

jdgashg 

或獲得多個匹配:

string s = "foo[%=bar%]baz[%=qux%]quux"; 
foreach (Match match in Regex.Matches(s, @"\[%=(.*?)%]")) 
{ 
    Console.WriteLine(match.Groups[1].Value); 
} 

輸出:

bar 
qux 

注意文字字符串被寫成@ 「......」。這意味着字符串內的反斜槓被視爲文字反斜槓,而不是轉義碼。在C#中編寫正則表達式時,這通常很有用,以避免必須將字符串內的所有反斜槓加倍。這裏沒有太大的區別,但是在更復雜的例子中,它會有更多幫助。

0
(?<=\[%=).*?(?=%]) 

將匹配這兩個分隔符(不匹配分隔符本身)之間的任何文本(包括換行符)。不支持嵌套分隔符。

遍歷所有匹配:

Regex my_re = new Regex(@"(?<=\[%=).*?(?=%\])", RegexOptions.Singleline); 
Match matchResults = my_re.Match(subjectString); 
while (matchResults.Success) { 
    // matched text: matchResults.Value 
    // match start: matchResults.Index 
    // match length: matchResults.Length 
    matchResults = matchResults.NextMatch(); 
} 
0
\[%=([^%]|%[^\]])*%\] 

這不依賴於任何貪婪運營商,因此應翻譯成任何正則表達式語言。你可能會也可能不會在意這一點。

+0

我喜歡這一個:D – Gumbo 2010-01-27 17:18:58

0

試試這個:

\[%=((?:[^%]|%[^\]])*)%] 
+0

是的,這個也看起來不錯;) – 2010-01-27 17:19:59

+0

@Nate C-K:是的,兩個白癡,一個想法。 – Gumbo 2010-01-27 17:21:39

+0

我在測試中遇到了一個C樣式註釋錯誤的正則表達式問題,所以現在解決方案會永久地被燒入我的大腦。 – 2010-01-27 17:32:57

2

你可以使用簡單的

\[%=(.*?)%\] 

,但你應該明白,它不會正確處理嵌套。如果內容可能跨越多行,則還需要指定RegexOption.Singleline以製作.*?交叉線邊界。

+0

沒有正則表達式可以處理嵌套。 – 2010-01-27 17:29:58

+1

@Nate - 當然可以。遞歸正則表達式。 – 2010-01-27 17:44:07

+0

不存在遞歸正則表達式這樣的事情(儘管人們可能會提出任何錯誤的想法)。如果它是遞歸的,那麼它根據定義是不規則的。 – 2010-01-27 17:49:14