我无法捕获括号。
我有一个包含这种形式数据的大文件:
I.u[12] = {n: "name1",...};
I.u[123] = {n: "name2",...};
I.u[1234] = {n: "name3",...};
我想创建一个系统,如果我提供 id(这里 , , ),可以帮助我从文件中获取名称(这里name1
, name2
, )。我有以下代码:name3
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]
但没有用。
我现在已经搜索了片刻没有成功。你知道出了什么问题吗?