Skip to main content
 首页 » 编程设计

c#之正则表达式:获取 id 列表

2024年02月25日28fff_TT

我需要从字符串中获取 id 列表。字符串的正则表达式是这样的:

"GET_LIST( [A-Za-z0-9]{5,10}){0,100}"; 

当我发送这样的字符串时:

GET_LIST 1000 10001 10002  

我想得到类似 "10000 10001 10002" 或更好的 id 列表。但是,当我尝试使用 matches.Groups[1].Value; 获取此信息时 我只得到最后一个ID。

我的代码实际上是这样的:

public IList<string> ExctractListId(string command) 
{ 
    IList<string> id = new List<string>(); 
    Match matches = new Regex(ReponseListeService).Match(command); 
    if (matches.Success) 
    { 
 
        string ids = matches.Groups[1].Value; 
        Console.WriteLine(ids); 
        return id; 
    } 
 
    return id; 
} 

我知道代码并不完全正确,其实我只是想得到一个包含所有id的列表或字符串

这段代码是作业,我不会用,Split(), Concat(), ...

我怎么能有这个?

请您参考如下方法:

你可以使用

private static string pattern = @"^GET_LIST(?:\s+([A-Za-z0-9]{4,10})){0,100}$"; 
private static List<string> ExtractListId(string command) 
{ 
    return Regex.Matches(command, pattern) 
        .Cast<Match>().SelectMany(p => p.Groups[1].Captures 
            .Cast<Capture>() 
            .Select(t => t.Value) 
        ) 
        .ToList(); 
} 

参见 C# demo和一个 regex demo .结果:

详情

  • ^ - 匹配字符串的开头
  • GET_LIST - 文字子串
  • (?:\s+([A-Za-z0-9]{4,10})){0,100} - 出现 0 到 100 次
    • \s+ - 1+ 个空格
    • ([A-Za-z0-9]{4,10}) - 捕获第 1 组:4 到 10 个字母数字 ASCII 字符
  • $ - 字符串结尾。

请注意,我们在量化的非捕获组 (?:.. .){0,100}。要获取这些值,您应该访问组捕获集合。由于组的 ID 为 1,您需要获取 match.Groups[1] 并访问其所有 .Captures。