2012-10-24 44 views
-1

例子:我想找到1234在一個字符串指定的目標:查找字符串

string target = "55555>>><<[1234]<>>>788"; 

我如何才能找到與[,]數不知道如何[]之前[或之後]之間多少數字?我需要我的項目的一個小代碼。

謝謝。

+2

聽起來像是正則表達式工作 –

+0

你能擁有比字符串中設置的[]嗎? – RobH

回答

1

這聽起來像是正則表達式

工作
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Text.RegularExpressions; 

namespace ConsoleApplication4 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string str = "55555>>><<[1234]<>>>788"; 

      Regex r = new Regex(@"\[(\d*)\]"); 
      Match match = r.Match(str); 
      Console.WriteLine(match.Groups[1].Value); 
     } 
    } 
} 

上面的代碼中有以下輸出

1234 
Press any key to continue . . . 
+0

感謝,這正是我需要的 – Krestek

3
using System.Text.RegularExpressions; 

... 

// Declare target 
string target = "55555>>><<[1234]<>>>788"; 

// Declare the regular expression 
Regex regex = new Regex(
    @"(?<=\[)[0-9]+(?=\])", 
    RegexOptions.None 
); 

// Use regex to get value 
string number = regex.Match(target).Value; 

// Convert to number (optional) 
int value = 0; 
int.TryParse(number, out value); 

// Note: value will be 0 if no matches are found. 

什麼這個表達式的作用:

第一位(?<=\[)是 「向後看」。它可以確保一個支架繼續進行編號。因爲括號是正則表達式中的特殊字符,所以必須使用反斜線進行轉義。

中間位[0-9]+尋找一個或多個任何數字的。如果你想零個或更多,你可以使用一顆星而不是一個加號:[0-9]*

最後一位(?=\])是一種類似於「後視」的「向前看」。支架再次逃脫。

的輸出將是唯一的數字沒有括號但只有當數由括號包圍。

+0

當我把代碼,VS無法理解正則表達式,我應該在代碼的開頭添加的東西嗎? – Krestek

+0

還有一個問題...如何將正則表達式值添加到名爲「target」的字符串? – Krestek

+0

您不想將正則表達式值添加到字符串中。您將創建一個正則表達式對象,該對象具有用於獲取值的「匹配」方法。我用例子更新了我的答案。 –

0

這裏是一個正則表達式該做的伎倆:

Console.WriteLine (Regex.Match("55555>>><<[1234]<>>>788", @"(?:\[)(?<Data>[^\]]+)(?:\])").Groups["Data"].Value); 
// 1234 is outputed 
0

的以下就足夠了:

var match = Regex.Match("55555>>><<[1234]<>>>788", ".*\[(.+)\].*"); 

var value = match.Groups[1].Value; //= "1234" 

如果值應該始終是一個數字,您可以用(\d+)替代(.+),就像在其他答案中一樣。

.+指任何字符
\d指任何數字0到9

+0

如果你使用'*'或'\ d *'然後這允許[]之間的0字符。使用'+'確保至少有一個字符/數字。 –