我写了以下正则表达式:
^(\[[0-9]+\])*$
它符合这些示例性文本:
""
"[0]"
"[0][1][2][0][9]"
我想要的是获取括号内存储的数字列表。如何优雅地做到这一点?
我的方法:
public static IEnumerable<int> GetNumbers(string text)
{
if (false == Regex.IsMatch(text, "^(\\[[0-9]+\\])*$"))
throw new FormatException();
return text
.Trim('[', ']')
.Split(new[] {"]["}, StringSplitOptions.None)
.Select(int.Parse);
}
答案 0 :(得分:2)
解决方案:
public static IEnumerable<int> GetNumbers(string text)
{
var match = Regex.Match(text, "^(\\[(?<number>[0-9]+)\\])*$");
if (!match.Success)
throw new FormatException();
var captures = match.Groups["number"].Captures;
foreach (Capture capture in captures)
yield return int.Parse(capture.Value);
}
答案 1 :(得分:0)
如果您无法更改模式,只能更改代码,则可以使用
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
var s1 = "[0][1][2][0][9]";
var res1 = string.Join(",", GetNumbers(s1).ToList()); // Many
Console.WriteLine(res1);
Console.WriteLine(string.Join(",", GetNumbers("[8]").ToList())); // One
Console.WriteLine(string.Join(",", GetNumbers("").ToList())); // Empty
}
public static IEnumerable<int> GetNumbers(string text)
{
if (string.IsNullOrWhiteSpace(text))
return Enumerable.Empty<int>(); // No text => return Empty
var match = Regex.Match(text, @"^(\[[0-9]+\])*$");
if (!match.Success) // No match => return Empty
return Enumerable.Empty<int>();
return match.Groups[1].Captures
.Cast<Capture>() // Get the captures
.Select(n => Int32.Parse(n.Value.Trim('[', ']'))); // Trim the brackets and parse
}
}
请参阅IDEONE demo