2
在C#中,我需要捕获短语* | variablename | *中的变量名。C#Regex如何捕获* |之间的所有内容和| *?
我有这个表达式:Regex regex = new Regex(@"\*\|(.*)\|\*");
在线正则表达式测试返回“VARIABLENAME”,但在C#代码,返回* | VARIABLENAME | *,或包括明星和酒吧字符的字符串。任何人都知道我为什么经历这种回报价值?
非常感谢!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RegExTester
{
class Program
{
static void Main(string[] args)
{
String teststring = "This is a *|variablename|*";
Regex regex = new Regex(@"\*\|(.*)\|\*");
Match match = regex.Match(teststring);
Console.WriteLine(match.Value);
Console.Read();
}
}
}
//Outputs *|variablename|*, instead of variablename
感谢BoltClock!如果我有 String teststring =“这是\ * | variablename | \ *确定我的\ * | friend | \ *”; 我需要使用MatchCollection方法,还是将该方法工作? –
你需要一个MatchCollection,是的。这意味着'MatchCollection matches = regex.Matches(teststring)'。您仍然会使用集合中每个*匹配的'Group'属性 - 只需循环它即可。 – BoltClock
非常感谢! –