C#正则表达式捕获括号
我在捕捉括号时遇到困难 我有一个大文件,其中包含以下表格的数据:C#正则表达式捕获括号,c#,regex,C#,Regex,我在捕捉括号时遇到困难 我有一个大文件,其中包含以下表格的数据: I.u[12] = {n: "name1",...}; I.u[123] = {n: "name2",...}; I.u[1234] = {n: "name3",...}; 我想创建一个系统,如果我提供id(此处12,123,1234),它可以帮助我从文件中获取名称(此处name1,name2,name3)。我有以下代码: public static string GetItemName(int id) {
I.u[12] = {n: "name1",...};
I.u[123] = {n: "name2",...};
I.u[1234] = {n: "name3",...};
我想创建一个系统,如果我提供id(此处12
,123
,1234
),它可以帮助我从文件中获取名称(此处name1
,name2
,name3
)。我有以下代码:
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]
,但都没有成功
我已经找了一会儿,但没有成功。你知道怎么回事吗?因为你指的是错误的组号..应该是
1
而不是0
组0
将始终包含整个匹配项,无论您有多少组
而且regex应该是
^I.u\["+id+@"\]\s*=\s*{n:\s*""(.+)"",.+};$
因为您引用了错误的组号。它应该是
1
而不是0
组0
将始终包含整个匹配项,无论您有多少组
正则表达式也应该是
^I.u\["+id+@"\]\s*=\s*{n:\s*""(.+)"",.+};$
根据您更新的问题,我可以看出您正在使用贪婪量词:
+
。这将尽可能匹配。您需要一个被动修饰符,该修饰符只匹配所需的数量:+?
试试这个:
Regex regex = new Regex(@"^I.u\["+id+@"\]\s=\s\{n:\s(?<Name>.+?),.+\};$", RegexOptions.Multiline);
根据您更新的问题,我可以看出您正在使用贪婪量词:
+
。这将尽可能匹配。您需要一个被动修饰符,该修饰符只匹配所需的数量:+?
试试这个:
Regex regex = new Regex(@"^I.u\["+id+@"\]\s=\s\{n:\s(?<Name>.+?),.+\};$", RegexOptions.Multiline);
正如其他人指出的那样,这:
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
正如其他人所指出的,这:
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你能解释为什么“m.Groups[1]…不起作用”?你能解释为什么“m.Groups[1]…不起作用”?OP说“m.Groups[1]…不起作用”,尽管他/她没有解释原因。OP说“m.Groups[1]…不起作用”,尽管他/她没有解释原因。