2010-01-20 21 views
3

請幫我解決這個問題。 我想將「-action = 1」分成「action」和「1」。幫我使用正則表達式分割字符串

string pattern = @"^-(\S+)=(\S+)$"; 
Regex regex = new Regex(pattern); 
string myText = "-action=1"; 
string[] result = regex.Split(myText); 

我不知道爲什麼結果長度= 4。

result[0] = "" 
result[1] = "action" 
result[2] = "1" 
result[3] = "" 

請幫幫我。

P/S:我正在使用.NET 2.0。

謝謝。

你好,我用字符串測試:@「 - destination = C:\ Program Files \ Release」但它有不準確的結果,我不明白爲什麼結果的長度= 1。我認爲,因爲它有一個空白區域串。

我想要拆分爲 「目的地」 & 「C:\ Program Files文件\發佈」

更多信息:這是我的要求: -string1 =字符串2 - >它拆分:字符串1 &字符串2。 在string1中& string2不包含字符:' - ','=',但它們可以包含空格。

請幫幫我。謝謝。

+0

你好,我用繩子測試:@「 - 目的地= C:\ Program Files文件\發佈」,但它有不準確的結果,我不明白爲什麼結果的長度= 1,我想是因爲它有一個字符串中的空白區域。 我想分割它到「目的地」和「C:\ Program Files文件\釋放」 請幫助我。謝謝。 –

回答

3

試試這個(更新添加Regex.Split):

string victim = "-action=1"; 
string[] stringSplit = victim.Split("-=".ToCharArray()); 
string[] regexSplit = Regex.Split(victim, "[-=]"); 

編輯:使用你的例子:

string input = @"-destination=C:\Program Files\Release -action=value"; 
foreach(Match match in Regex.Matches(input, @"-(?<name>\w+)=(?<value>[^=-]*)")) 
{ 
    Console.WriteLine("{0}", match.Value); 
    Console.WriteLine("\tname = {0}", match.Groups["name" ].Value); 
    Console.WriteLine("\tvalue = {0}", match.Groups["value"].Value); 
} 
Console.ReadLine(); 

當然,這段代碼有問題,如果你的路徑包含-字符

0

使用string.split()有什麼問題?

string test = "-action=1"; 
string[] splitUp = test.Split("-=".ToCharArray()); 

我承認,但是這仍然給你可能更多的參數比你想的分裂數組中看到...

[0] = "" 
[1] = "action" 
[2] = "1" 
+0

怎麼了?你不需要免費的輸入驗證,它可以處理不同的事情(想象一下'-range = 1-2')。 – Lucero

+0

已授予,但使用RegEx,您不會獲得任何*任何*免費,並且正如OP所見,構建適當的正則表達式字符串並不是一項簡單的任務。我只是建議一個合理可行的替代方案,它不依賴於瞭解未知(請參閱OP的編輯) – ZombieSheep

5

不要使用分割,只需要使用Match ,然後按索引(索引1和索引2)從Groups集合中獲得結果。

Match match = regex.Match(myText); 
if (!match.Success) { 
    // the regex didn't match - you can do error handling here 
} 
string action = match.Groups[1].Value; 
string number = match.Groups[2].Value; 
+0

您絕對不應該在.NET正則表達式中按索引使用組......您可以將組命名爲某個原因。想象一下,如果有人稍後通過添加另一組括號稍微改變了正則表達式。那麼你不得不改變你所有的索引。 - 改用組名。 –

+0

我只使用非常簡單的情況下的索引,如這個(只有一個或兩個捕獲,沒有嵌套組等)。否則,我同意使用名稱可以使正則表達式更健壯,更易於理解。 – Lucero

+0

你好,我用字符串測試:@「 - destination = C:\ Program Files \ Release」但它有不準確的結果。我想是因爲它有一個字符串的空白區域。 我想將它拆分爲「目的地」和「C:\ Program Files \ Release」 –

3

在.NET Regex中,你可以命名你的組。

string pattern = @"^-(?<MyKey>\S+)=(?<MyValue>\S+)$"; 
Regex regex = new Regex(pattern); 
string myText = "-action=1"; 

然後做一個「匹配」,並獲取您的組名稱的值。

Match theMatch = regex.Match(myText); 
if (theMatch.Success) 
{ 
    Console.Write(theMatch.Groups["MyKey"].Value); // This is "action" 
    Console.Write(theMatch.Groups["MyValue"].Value); // This is "1" 
} 
相關問題