繁体   English   中英

C# 正则表达式匹配数组

[英]C# Regex Match Array

所以这是我第一次真正使用 C#,我在使用正则表达式时遇到了一些麻烦。 所以我有一个这样的字符串:

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

我正在捕获=;之间的所有内容; 所以:

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

但是,我无法从数组中获取结果:

string str2 = matches[0].Value;

我不确定我做错了什么。 任何帮助表示赞赏!

编辑:所以这是我试图实现的(使用@Jason Evans 代码):

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];

请尝试以下操作:

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>)来捕获“=”前后的文本。 这样您就可以抓取字符串的各个部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM