C# 正则表达式在字符串中多次匹配

C# 正则表达式在字符串中多次匹配,c#,regex,C#,Regex,我试图从介于>之间的字符串中提取值。但它们可能会发生多次 任何人都可以帮助正则表达式匹配这些 this is a test for <<bob>> who like <<books>> test 2 <<frank>> likes nothing test 3 <<what>> <<on>> <<earth>> <<this>>

我试图从介于>之间的字符串中提取值。但它们可能会发生多次

任何人都可以帮助正则表达式匹配这些

this is a test for <<bob>> who like <<books>>
test 2 <<frank>> likes nothing
test 3 <<what>> <<on>> <<earth>> <<this>> <<is>> <<too>> <<much>>.
这是一个测试谁喜欢
测试2什么都不喜欢
测试3。
然后,我想对GroupCollection进行foreach,以获取所有值

得到的任何帮助都是巨大的。
谢谢。

您可以尝试以下方法之一:

(?<=<<)[^>]+(?=>>)
(?<=<<)\w+(?=>>)
(?)
(?类似这样的内容:

(<<(?<element>[^>]*)>>)*
(>)*
此程序可能有用:


使用肯定的向前看和向后看断言匹配尖括号,使用
*?
匹配这些括号之间尽可能短的字符序列。通过迭代
Matches()
方法返回的
MatchCollection
查找所有值

Regex regex = new Regex("(?<=<<).*?(?=>>)");

foreach (Match match in regex.Matches(
    "this is a test for <<bob>> who like <<books>>"))
{
    Console.WriteLine(match.Value);
}
Regex Regex=new Regex((?虽然这是使用lookarounds进行左右上下文检查的一个很好的例子,但我还想添加一种LINQ(lambda)方法来访问匹配项/组,并展示当您只想提取模式的一部分时方便使用的简单数字:

using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;

// ...

var results = Regex.Matches(s, @"<<(.*?)>>", RegexOptions.Singleline)
            .Cast<Match>()
            .Select(x => x.Groups[1].Value);
注意

  • 是与
  • RegexOptions.Singleline
    使
    也匹配换行符(LF)字符(默认情况下不匹配)
  • Cast()
    将匹配集合强制转换为
    IEnumerable
    ,您可以使用lambda进一步访问该集合
  • Select(x=>x.Groups[1].Value)
    仅从当前
    x
    match对象返回组1值
  • 注意:您可以通过在
    选择之后添加
    .ToList()
    .ToArray()
    来进一步创建获取值的数组列表
在中,
string.Join(“,”,results)
生成以逗号分隔的第1组值字符串:

var strs = new List<string> { "this is a test for <<bob>> who like <<books>>",
                              "test 2 <<frank>> likes nothing",
                              "test 3 <<what>> <<on>> <<earth>> <<this>> <<is>> <<too>> <<much>>." };
foreach (var s in strs) 
{
    var results = Regex.Matches(s, @"<<(.*?)>>", RegexOptions.Singleline)
            .Cast<Match>()
            .Select(x => x.Groups[1].Value);
    Console.WriteLine(string.Join(", ", results));
}

没有双关语的意思,但这正是我想要的。谢谢你的快速回复。
var strs = new List<string> { "this is a test for <<bob>> who like <<books>>",
                              "test 2 <<frank>> likes nothing",
                              "test 3 <<what>> <<on>> <<earth>> <<this>> <<is>> <<too>> <<much>>." };
foreach (var s in strs) 
{
    var results = Regex.Matches(s, @"<<(.*?)>>", RegexOptions.Singleline)
            .Cast<Match>()
            .Select(x => x.Groups[1].Value);
    Console.WriteLine(string.Join(", ", results));
}
bob, books
frank
what, on, earth, this, is, too, much