1

我无法捕获括号。

我有一个包含这种形式数据的大文件:

I.u[12] = {n: "name1",...};
I.u[123] = {n: "name2",...};
I.u[1234] = {n: "name3",...};

我想创建一个系统,如果我提供 id(这里 , , ),可以帮助我从文件中获取名称(这里name1, name2, )。我有以下代码:name3121231234

    public static string GetItemName(int id)
    {
        Regex regex = new Regex(@"^I.u\["+id+@"\]\s=\s{n:\s(.+),.+};$");
        Match m= GetMatch(regex,filepath);
        if(m.Success) return m.Groups[0].Value;
        else return "unavailable";
    }

    public static Match GetMatch(Regex regex, string filePath)
    {
        Match res = null;
        using (StreamReader r = new StreamReader(filePath))
        {
            string line;
            while ((line = r.ReadLine()) != null)
            {
                res = regex.Match(line);
                if (res.Success) break;
            }
        }
        return res;
    }

正则表达式在文件中找到正确的行,但我真的不知道为什么它没有按我的意愿提取名称,并且,

if(m.Success) return m.Groups[0].Value;

返回文件中的整行而不是名称...我尝试了很多东西,甚至更改m.Groups[0]m.Groups[1]但没有用。

我现在已经搜索了片刻没有成功。你知道出了什么问题吗?

4

3 回答 3

3

根据您更新的问题,我可以看到您正在使用贪婪量词:.+。这将尽可能匹配。您需要一个被动修饰符,它只会匹配必要的部分:.+?

尝试这个:

Regex regex = new Regex(@"^I.u\["+id+@"\]\s=\s\{n:\s(?<Name>.+?),.+\};$", RegexOptions.Multiline);

然后:

if(m.Success) return m.Groups["Name"].Value;
于 2013-01-16T17:02:41.537 回答
2

正如其他人指出的那样:

if(m.Success) return m.Groups[0].Value;

应该:

if(m.Success) return m.Groups[1].Value;

但是,这将返回"name1"包括引号。尝试将您的正则表达式模式修改为:

@"^I.u\["+id+@"\]\s=\s{n:\s""(.+)"",.+};$"

这将排除引号m.Groups[1].Value

于 2013-01-16T17:04:34.463 回答
0

因为您指的是错误的组号..应该1不是0

0无论您有多少组,组都将始终包含整个匹配项。

正则表达式也应该是

^I.u\["+id+@"\]\s*=\s*{n:\s*""(.+)"",.+};$
于 2013-01-16T17:01:01.217 回答