2012-12-20 192 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; 
}