2015-10-16 321 views
2

所以這是我第一次使用C#的實時,我有一些使用正則表達式的麻煩。 所以我有這樣的字符串:C#正則表達式匹配數組

string str = "test=CAPTURE1; test2=CAPTURE2; ......."

=;之間捕捉一切,所以:

var matches = Regex.Matches(str, "=([^;]*);/g");

但是,我不能得到的結果出來的array:

string str2 = matches[0].Value;

我不知道我在做什麼錯。任何幫助表示讚賞!

編輯: 所以這裏就是我想實現這(使用@Jason埃文斯代碼):

string connection = "Server=localhost;Database=dbTest;User Id=hello;Password=world;";    
var matches = Regex.Matches(connection, "(?<Key>[^=]*)=(?<Value>[^;]*)"); 

string server = matches[0].Groups["Data"].Value; 
string db = matches[1].Groups["Data"].Value; 
string un = matches[2].Groups["Data"].Value; 
string pw = matches[3].Groups["Data"].Value;   

MsSqlConnectionParameters param = (MsSqlConnectionParameters)e.ConnectionParameters; 
param.ServerName = server; 
param.DatabaseName = db; 
param.UserName = un; 
param.Password = pw; 

這仍然不是出於某種原因的工作,雖然我相信這是對。

EDIT2:什麼奇怪的是,這工作(使用相同的數據)......我很爲難:

string[] test = { "localhost", "dbTest", "hello", "world" }; 

MsSqlConnectionParameters param = (MsSqlConnectionParameters)e.ConnectionParameters; 

param.ServerName = test[0]; 
param.DatabaseName = test[1]; 
param.UserName = test[2]; 
param.Password = test[3]; 
+0

全局標誌由'Regex.Matches()'方法隱含。雖然看到這裏使用全局標誌,但它不是像JS一樣完成:https://msdn.microsoft.com/en-us/library/b49yw9s8%28v=vs.110%29.aspx – Pluto

+0

我試過你例如刪除'/ g'在你的正則表達式的結尾,它按預期工作。你在用什麼? – Luiso

+0

@Luiso我已更新我的文章,以便您可以看到我的實施 –

回答

2

嘗試以下操作:

namespace ConsoleApplication1 
{ 
    using System.Text.RegularExpressions; 

    public class Program 
    { 
     static void Main(string[] args) 
     { 
      string str = "test=CAPTURE1; test2=CAPTURE2"; 

      var matches = Regex.Matches(str, "(?<Key>[^=]*)=(?<Value>[^;]*)"); 

      string str2 = matches[0].Groups["Key"].Value; 
      string str3 = matches[0].Groups["Value"].Value; 
     } 
    } 
} 

我使用了一個名爲捕獲在'='之前和之後的組(?<Key>)(?<Data>)。這樣你可以抓住字符串的各個部分。

+0

是的,我認爲這是對的 - 但我仍然有問題將價值傳遞給我需要的東西。我已更新我的帖子以包含我的實施。 –