2015-10-16 323 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

是的,我认为这是对的 - 但我仍然有问题将价值传递给我需要的东西。我已更新我的帖子以包含我的实施。 –