在标签之间获取文本

Dea*_*ean 1 c# regex

嘿,我有一个输入字符串,如下所示:

Just a test Post [c] hello world [/c] 
Run Code Online (Sandbox Code Playgroud)

输出应该是:

你好,世界

任何人都可以帮忙吗?

我试着用:

Regex regex = new Regex("[c](.*)[/c]");
var v = regex.Match(post.Content);
string s = v.Groups[1].ToString();
Run Code Online (Sandbox Code Playgroud)

hor*_*rgh 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;
}
Run Code Online (Sandbox Code Playgroud)

并使用它:

string s = "Just a test Post [c] hello world [/c] ";
string res = s.GetStrBetweenTags("[c]", "[/c]");
Run Code Online (Sandbox Code Playgroud)


Ria*_*Ria 5

在正则表达式

[character_group]
Run Code Online (Sandbox Code Playgroud)

手段:

匹配任何单个字符character_group.

请注意,\, *, +, ?, |, {, [, (,), ^, $,., #并且white space字符转义,您必须\在表达式中使用它们:

\[c\](.*)\[/c\]
Run Code Online (Sandbox Code Playgroud)

\正则表达式中的反斜杠字符表示其后面的字符是特殊字符,或者应按字面解释.

以便在编辑正则表达式时,您的代码应该正常工作:

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