2011-09-15 91 views
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 

回答

12

match.Value包含整个比赛。这包括分隔符,因为您在正则表达式中指定了它们。当我测试你的正则表达式并输入RegexPal时,它突出显示*|variablename|*

你想只捕获组(括号中的内容),所以使用match.Groups[1]

String teststring = "This is a *|variablename|*"; 
Regex regex = new Regex(@"\*\|(.*)\|\*"); 
Match match = regex.Match(teststring); 
Console.WriteLine(match.Groups[1]); 
+0

感谢BoltClock!如果我有 String teststring =“这是\ * | variablename | \ *确定我的\ * | friend | \ *”; 我需要使用MatchCollection方法,还是将该方法工作? –

+0

你需要一个MatchCollection,是的。这意味着'MatchCollection matches = regex.Matches(teststring)'。您仍然会使用集合中每个*匹配的'Group'属性 - 只需循环它即可。 – BoltClock

+0

非常感谢! –

相关问题