C# 获取大字符串中分隔符之间的所有值

C# 获取大字符串中分隔符之间的所有值,c#,regex,string,C#,Regex,String,我有一个字符串,它有一堆文本。我需要找到位于之间的所有值 'site.com/PI/'和'/500/item.jpg 例如: String STRING = @" http://site.com/PI/0/500/item.jpg blah-blah http://site.com/PI/1/500/item.jpg blah-blah http://site.com/PI/2/500/item.jpg blah-blah http://site.com/PI/4/500/item.jpg bl

我有一个字符串,它有一堆文本。我需要找到位于之间的所有值 'site.com/PI/'和'/500/item.jpg

例如:

String STRING = @"
http://site.com/PI/0/500/item.jpg
blah-blah
http://site.com/PI/1/500/item.jpg
blah-blah
http://site.com/PI/2/500/item.jpg
blah-blah
http://site.com/PI/4/500/item.jpg
blah-blah
http://site.com/PI/8/500/item.jpg
blah-blah
http://site.com/PI/6/500/item.jpg    blah-blah"
需要获取{0,1,2,4,8,6}的列表

使用正则表达式很容易获得一个事件:

Regex.Match(STRING, @"(?<=/PI/).*(?=/500/)").Value;

Regex.Match(STRING,@)(?您可以使用
Matches
函数进行匹配。它将返回
Match
对象的集合

var matches = Regex.Matches(STRING, @"(?<=/PI/).*(?=/500/)")
foreach(Match match in matches)
{
  Console.WriteLine(match.Value);
}

var matches=Regex.matches(STRING,@)(?您可以使用
matches
函数进行此操作。它将返回
Match
对象的集合

var matches = Regex.Matches(STRING, @"(?<=/PI/).*(?=/500/)")
foreach(Match match in matches)
{
  Console.WriteLine(match.Value);
}
var matches=Regex.matches(字符串,@)(?您可以使用LINQ

List<string> matches = Regex.Matches(STRING, @"(?<=/PI/).*(?=/500/)")
                            .Cast<Match>()
                            .Select(m => m.Value)
                            .ToList();
List matches=Regex.matches(字符串,@)(?您可以使用LINQ

List<string> matches = Regex.Matches(STRING, @"(?<=/PI/).*(?=/500/)")
                            .Cast<Match>()
                            .Select(m => m.Value)
                            .ToList();

List matches=Regex.matches(STRING,@)(?我以前从未这样做过-当我使用您的示例时,我的语法是红色高亮显示的,无法编译。MatchCollection不实现
IEnumerable
,只实现
IEnumerable
。相反,
Regex.matches(bla,bla).Cast().Select…
of type
是不必要的,因为
MatchCollection
中的所有项都保证为
Match
类型。如果它们是匹配的,则测试它们是浪费的。因此,
.Cast
更合适。@spender:简单的测试真的比Cast更糟糕吗(以前从未这样做过-当我使用您的示例时,我的语法是红色高亮显示的,无法编译。MatchCollection不实现
IEnumerable
,只实现
IEnumerable
。相反,
Regex.Matches(bla,bla).Cast().Select…
of type
是不必要的,因为
MatchCollection
中的所有项都保证为
Match
类型。如果它们是匹配的,则测试它们是浪费的。因此,
.Cast
更合适。@spender:简单的测试真的比Cast更糟糕吗?