嘿,我有一个输入字符串,看起来像这样:获取标签
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();
嘿,我有一个输入字符串,看起来像这样:获取标签
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();
在正则表达式
[character_group]
表示:
匹配任何单个字符
character_group
。
注意\, *, +, ?, |, {, [, (,), ^, $,., #
和white space
是Character Escapes,你必须使用\
在表达式中使用它们:
\[c\](.*)\[/c\]
在正则表达式中的反斜杠字符\
表明它后面的字符或者是一个特殊的字符,或者应该从字面上解释。
,使你的代码应能正常工作,如果您编辑您的正则表达式:
Regex regex = new Regex("\[c\](.*)\[/c\]");
var v = regex.Match(post.Content);
string s = v.Groups[1].ToString();
你的代码更改为:
Regex regex = new Regex(@"\[c\](.*)\[/c\]");
var v = regex.Match(post.Content);
string s = v.Groups[1].Value;
你在找这样的事情?
var regex = new Regex(@"(?<=\[c\]).*?(?=\[/c\])");
foreach(Match match in regex.Matches(someString))
Console.WriteLine(match.Value);
你可以做到这一点没有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]");
捎带上@ 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;
}
我试图用正则表达式但它没有工作 – Dean
更清晰 –
你可以在线测试你的正则表达式 –