我需要从字符串中获取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(),...
我该怎么办?
答案 0 :(得分:2)
您可以使用
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字符$
- 字符串结束。请注意,我们在量化的非捕获组([A-Za-z0-9]{4,10})
中有一个捕获组((?:...){0,100}
)。要获取这些值,您应该访问组捕获集合。由于该群组的ID为1,您需要获取match.Groups[1]
并访问其所有.Captures
。
答案 1 :(得分:1)
您还可以使用String.Split()
方法在空格字符上拆分字符串,然后将所有可以解析的项目返回到int
。请注意,这将返回有效整数的所有项,因此它将与您的示例输入一起使用,但如果您有其他类型的输入,则可能需要进行一些修改。
public static IList<string> ExctractListId(string command)
{
if (command == null || !command.StartsWith("GET_LIST"))
{
return new List<string>();
}
int temp;
return command.Split().Where(item => int.TryParse(item, out temp)).ToList();
}
使用示例:
private static void Main()
{
Console.WriteLine(string.Join(", ", ExctractListIds("GET_LIST 1000 10001 10002")));
GetKeyFromUser("\nDone! Press any key to exit...");
}
<强>输出强>
答案 2 :(得分:0)
您正在搜索的数据包含空白区域。因此,在正则表达式中添加white-space
或\s
并重试。
希望这有帮助。
抱歉,我没有完全理解这个问题。
使用Javascript的小代码段
function getId(data){
var regex = /^GET_LIST(([\d\s]{5,10}){0,100})/g;
var match = regex.exec(data);
console.log(match[1]);
}