2011-02-03 108 views
10

我試圖從字符串中提取值在<和<之間的值。但他們可能會發生多次。RegEx在字符串中多次匹配

任何人都可以幫助正則表達式來匹配這些;

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

然後我想要通過GroupCollection來獲取所有值。

大大收到的任何幫助。 謝謝。

回答

28

使用提前了積極的外觀和向後看斷言相匹配的尖括號,用.*?匹配這些括號之間最短的字符序列。通過迭代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); 
} 
+0

沒有雙關語意,但這正是我所追求的。非常感謝您的快速回復。 – 2011-02-03 22:40:23

1

您可以嘗試下列操作之一:

(?<=<<)[^>]+(?=>>) 
(?<=<<)\w+(?=>>) 

然而,你將不得不遍歷返回MatchCollection。