我有以下形式的字符串:“t1 v2”。我需要 t 和 v 之后的数字,看起来很简单,我在做:
Regex regex = new Regex("t([0-9])");
MatchCollection matches = regex.Matches(options);
if (matches.Count > 0) {
foreach (Match match in matches) {
CaptureCollection captures = match.Captures;
Debug.Log(captures[0].Value);
}
}
我尝试了其他一些方法,但它总是返回“t1”,我需要它返回“1”。
我在这里错过了什么?
请您参考如下方法:
你没有遗漏任何东西,你只需要从结果中选择正确的捕获:
var options = "t1 v2";
var result = Regex.Matches(options, "[a-zA-Z]([0-9]+)").Cast<Match>().Select(x => int.Parse(x.Groups[1].Value)).ToList();
Console.WriteLine(string.Join(";", result));//1;2
或者更直接
result = Regex.Matches(options, "[a-zA-Z](?<foo>[0-9]+)", RegexOptions.ExplicitCapture).Cast<Match>().Select(x => int.Parse(x.Groups["foo"].Value)).ToList();
Console.WriteLine(string.Join(";", result));//1;2
在您的 Regex 查询中(重要的是,您的查询将丢失 't32' 等字符串):
result = Regex.Matches(options, "t([0-9])").Cast<Match>().Select(x => int.Parse(x.Groups[1].Value)).ToList();
Console.WriteLine(string.Join(";", result));//1
