RegEx 在字符串中多次匹配 [英] RegEx Match multiple times in string

查看:56
本文介绍了RegEx 在字符串中多次匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to extract values from a string which are between << and >>. But they could happen multiple times.

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

Can anyone help with the regular expression to match these;

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

然后我想为每个 GroupCollection 获取所有值.

I then want to foreach the GroupCollection to get all the values.

任何帮助都非常受欢迎.谢谢.

Any help greatly received. Thanks.

推荐答案

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

Use a positive look ahead and look behind assertion to match the angle brackets, use .*? to match the shortest possible sequence of characters between those brackets. Find all values by iterating the MatchCollection returned by the Matches() method.

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

foreach (Match match in regex.Matches(
    "this is a test for <<bob>> who like <<books>>"))
{
    Console.WriteLine(match.Value);
}

DotNetFiddle 中的 LiveDemo

这篇关于RegEx 在字符串中多次匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆