gpt4 book ai didi

c# - RegEx 在字符串中多次匹配

转载 作者:IT王子 更新时间:2023-10-29 04:26:28 24 4
gpt4 key购买 nike

我正在尝试从 << 和 >> 之间的字符串中提取值。但它们可能会发生多次。

谁能帮忙用正则表达式来匹配这些;

this is a test for <<bob>> who like <<books>>
test 2 <<frank>> likes nothing
test 3 <<what>> <<on>> <<earth>> <<this>> <<is>> <<too>> <<much>>.

然后我想 foreach GroupCollection 以获取所有值。

大大收到任何帮助。谢谢。

最佳答案

使用正向前瞻和后视断言来匹配尖括号,使用 .*? 来匹配这些括号之间可能的最短字符序列。通过迭代 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);
}

LiveDemo in DotNetFiddle

关于c# - RegEx 在字符串中多次匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4892452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com