所以这是我第一次使用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];
全局标志由'Regex.Matches()'方法隐含。虽然看到这里使用全局标志,但它不是像JS一样完成:https://msdn.microsoft.com/en-us/library/b49yw9s8%28v=vs.110%29.aspx – Pluto
我试过你例如删除'/ g'在你的正则表达式的结尾,它按预期工作。你在用什么? – Luiso
@Luiso我已更新我的文章,以便您可以看到我的实施 –