C# 正则表达式匹配[和]之间的任何字符串
我想匹配[和]之间的任何字符串。以下代码工作正常,但我希望输出时不带此符号[] 我的代码:C# 正则表达式匹配[和]之间的任何字符串,c#,C#,我想匹配[和]之间的任何字符串。以下代码工作正常,但我希望输出时不带此符号[] 我的代码: string strValue = "{test}dfdgf[sms]";// i want to sms private void Form1_Load(object sender, EventArgs e) { Match mtch = Regex.Match(strValue, @"\[((\s*?.*?)*?)\]"); if (mtch.
string strValue = "{test}dfdgf[sms]";// i want to sms
private void Form1_Load(object sender, EventArgs e)
{
Match mtch = Regex.Match(strValue, @"\[((\s*?.*?)*?)\]");
if (mtch.Success)
{
MessageBox.Show(mtch.Value);
}
}
试一试
这将为您提供第一个捕获组的值—外部主题的内容。您将要使用属性。由于您已经在使用方括号,因此可以获得所需的组
MessageBox.Show(mtch.Groups[1].Value);
组[0]将包含带[and]的整个字符串
另外,我认为你的正则表达式可以简化
\[((\s*?.*?)*?)\]
应该相当于
\[(.*?)\]
因为。*将匹配任何内容,包括\s覆盖的空白
\[(.*?)\]