2012-12-20 189 views
0
之間的文本

嘿,我有一個輸入字符串,看起來像這樣:獲取標籤

Just a test Post [c] hello world [/c] 

輸出應該是:

的hello world

任何人可以幫助?

我試着使用:

Regex regex = new Regex("[c](.*)[/c]"); 
var v = regex.Match(post.Content); 
string s = v.Groups[1].ToString(); 
+0

我試圖用正則表達式但它沒有工作 – Dean

+0

更清晰 –

+0

你可以在線測試你的正則表達式 –

回答

5

在正則表達式

[character_group] 

表示:

匹配任何單個字符character_group

注意\, *, +, ?, |, {, [, (,), ^, $,., #white spaceCharacter Escapes,你必須使用\在表達式中使用它們:

\[c\](.*)\[/c\] 

在正則表達式中的反斜槓字符\表明它後面的字符或者是一個特殊的字符,或者應該從字面上解釋。

,使你的代碼應能正常工作,如果您編輯您的正則表達式:

Regex regex = new Regex("\[c\](.*)\[/c\]"); 
var v = regex.Match(post.Content); 
string s = v.Groups[1].ToString(); 
0

你的代碼更改爲:

Regex regex = new Regex(@"\[c\](.*)\[/c\]"); 
var v = regex.Match(post.Content); 
string s = v.Groups[1].Value; 
0

你在找這樣的事情?

var regex = new Regex(@"(?<=\[c\]).*?(?=\[/c\])"); 
foreach(Match match in regex.Matches(someString)) 
    Console.WriteLine(match.Value); 
7

你可以做到這一點沒有Regex。考慮這個擴展方法:

public static string GetStrBetweenTags(this string value, 
             string startTag, 
             string endTag) 
{ 
    if (value.Contains(startTag) && value.Contains(endTag)) 
    { 
     int index = value.IndexOf(startTag) + startTag.Length; 
     return value.Substring(index, value.IndexOf(endTag) - index); 
    } 
    else 
     return null; 
} 

,並使用它:

string s = "Just a test Post [c] hello world [/c] "; 
string res = s.GetStrBetweenTags("[c]", "[/c]"); 
1

捎帶上@ horgh的答案,這增加了一個包容/獨家選項:

public static string ExtractBetween(this string str, string startTag, string endTag, bool inclusive) 
{ 
    string rtn = null; 

    int s = str.IndexOf(startTag); 
    if (s >= 0) 
    { 
     if(!inclusive) 
      s += startTag.Length; 

     int e = str.IndexOf(endTag, s); 
     if (e > s) 
     { 
      if (inclusive) 
       e += startTag.Length; 

      rtn = str.Substring(s, e - s); 
     } 
    } 

    return rtn; 
}