2011-09-15 90 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

非常感謝! –

相關問題