簡體   English   中英

C#正則表達式捕獲括號

[英]C# Regex capturing parentheses

我在捕獲括號時遇到問題。

我有一個包含這種形式數據的大文件:

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;

正如其他人指出的那樣:

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排除引號

因為您指的是錯誤的組號。它應該是1而不是0

不論您有多少組,組0始終包含整個比賽。

正則表達式也應該是

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM