2009-06-17 85 views
4

首先,我在C#中,這就是我正在處理的RegEx的味道。這裏有一點事情,我需要能夠匹配:正則表達式將方括號內的括號內的數字與可選文本相匹配

[(1)] 

[(34) Some Text - Some Other Text] 

所以基本上我需要知道什麼是括號內爲數字而忽略了右括號之間的一切,近方括號。任何RegEx大師關心幫助?

+0

請您澄清一下嗎? – 2009-06-17 21:40:03

回答

15

這應該工作:

\[\(\d+\).*?\] 

如果你需要捕捉的號碼,只需用小括號括\d+

\[\((\d+)\).*?\] 
0

喜歡的東西:

\[\(\d+\)[^\]]*\] 
一些

可能需要更多轉義?

1

你必須匹配[]嗎?你可以做...

\((\d+)\) 

(數字本身將在組中)。

例如...

var mg = Regex.Match("[(34) Some Text - Some Other Text]", @"\((\d+)\)"); 

if (mg.Success) 
{ 
    var num = mg.Groups[1].Value; // num == 34 
} 
    else 
{ 
    // No match 
} 
0

如何 「^ \ [\((d +)\)」(perl的風格,不熟悉C#)。我想你可以放心地忽略其餘部分。

0

取決於你想實現什麼......

List<Boolean> rslt; 
String searchIn; 
Regex regxObj; 
MatchCollection mtchObj; 
Int32 mtchGrp; 

searchIn = @"[(34) Some Text - Some Other Text] [(1)]"; 

regxObj = new Regex(@"\[\(([^\)]+)\)[^\]]*\]"); 

mtchObj = regxObj.Matches(searchIn); 

if (mtchObj.Count > 0) 
    rslt = new List<bool>(mtchObj.Count); 
else 
    rslt = new List<bool>(); 

foreach (Match crntMtch in mtchObj) 
{ 
    if (Int32.TryParse(crntMtch.Value, out mtchGrp)) 
    { 
     rslt.Add(true); 
    } 
} 
0

這個怎麼樣?假設你只需要確定該字符串是否匹配,而不必提取數值...

 string test = "[(34) Some Text - Some Other Text]"; 

     Regex regex = new Regex("\\[\\(\\d+\\).*\\]"); 

     Match match = regex.Match(test); 

     Console.WriteLine("{0}\t{1}", test, match.Success); 
0

正則表達式好像在這種情況下矯枉過正。這是我最終使用的解決方案。

var src = test.IndexOf('(') + 1; 
var dst = test.IndexOf(')') - 1; 
var result = test.SubString(src, dst-src); 
相關問題