Skip to main content
 首页 » 编程设计

C# 正则表达式捕获括号

2024年02月02日29yxwkf

我无法捕捉括号。

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

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

我想创建一个系统来帮助我从文件中获取名称(此处为 name1、name2、name3),如果我提供 ID(此处为 12、123、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] 更改为 m.Groups[1] 但它没有用。

我现在已经搜索了片刻,但没有成功。您知道哪里出了问题吗?

请您参考如下方法:

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

试试这个:

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

然后:

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