C# 正则表达式捕获括号

标签 c# regex

我无法捕捉括号。

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

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

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

    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;

关于C# 正则表达式捕获括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14363672/

相关文章:

c# - WebBrowser 控件忽略来自 POST 请求的 302 重定向?

c# - 使用页面 anchor 请求导航到超链接

C# 按对象搜索组合框的索引

ios - 在不删除分隔符的情况下截断分隔的 NSString

ruby - 比 gsub(/\d|\W/, "") 更短的删除非字符的方法

java - 建议用 Java 创建一个翻译器

c# - Wpf 如何将 xaml.cs 窗口逻辑分离到单独的类中

c# - 在 c# 中使用 [] 接口(interface)(不是来自 ILIst)构建对象

regex - 编辑捕获组值

python - 正则表达式:如果后面跟着一组运算符,如何捕获括号组?