C#正则表达式捕获括号

时间:2013-01-16 16:59:02

标签: c# regex

我无法捕捉括号。

我有一个包含此格式数据的大文件:

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

如果我提供了ID,我想创建一个系统,帮助我从文件中获取名称(此处为name1name2name3)(此处{{1} },12123)。我有以下代码:

1234

正则表达式在文件中找到了正确的行,但我真的不知道它为什么不提取我想要的名称,

    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]但它没有用。

我现在搜索了一会儿但没有成功。你知道出了什么问题吗?

3 个答案:

答案 0 :(得分:3)

根据您更新的问题,我可以看到您使用的是贪婪量词:.+。这将尽可能匹配。您需要一个被动修改器,它只会根据需要进行匹配:.+?

试试这个:

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

然后:

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

答案 1 :(得分: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

中排除引号

答案 2 :(得分:0)

因为您指的是错误的组号。它应该是1而不是0

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

正则表达式应该是

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