2014-09-06 28 views
0

學習正則表達式。採取一切,除非它看到foo

我想匹配所有東西,除非它看到foo

輸入:

take everything 1 foo take everything 2 foo take everything 3 
take everything 4 

期望值:

match 1 : `take everything 1 ` 
match 2 : ` take everything 2 ` 
match 3 : ` take everything 3 ` 
match 4 : `take everything 4` 

嘗試:

  1. ([^foo]*)http://regex101.com/r/rT0wU0/1

    結果:

    匹配1:take everything 1

    匹配2-4,6-8,10:

    匹配5:take everything 2

    匹配9:take everything 3 take everything 4

  2. (.*(?!foo))http://regex101.com/r/hL4gP7/1

    結果:

    匹配1:take everything 1 foo take everything 2 foo take everything 3

    匹配2,3:

    匹配4:take everything 4

請告訴我。

+0

可能增加一些F或Ø到您的字符串,看看爲什麼第一個失敗了呢?對於第二個,我會嘗試'。*?'而不是'。*'(只是猜測,沒有測試過) – mihi 2014-09-06 17:24:36

回答

2

使用字邊界\b連同負向預測。

\b(?:(?!foo).)+ 

例子:

String s = @"take everything 1 foo take everything 2 foo take everything 3 
take everything 4"; 

foreach (Match m in Regex.Matches(s, @"\b(?:(?!foo).)+")) 
     Console.WriteLine(m.Value.Trim()); 

輸出

take everything 1 
take everything 2 
take everything 3 
take everything 4 
+0

謝謝,這也是工作 – tsuta 2014-09-06 17:28:55

1

你可以試試下面的正則表達式,

(?<=foo|^)(.*?)(?=foo|$) 

DEMO

  • (?<=foo|^) Lookafter foo或行的開始。
  • (.*?)匹配所有字符串foo或行尾。
+0

3和4不匹配 – tsuta 2014-09-06 17:26:14

+0

對不起,我錯過了'm'多行 – tsuta 2014-09-06 17:28:12

+0

是的,你需要添加'm'修飾符以使正則表達式能夠在多行上工作。 – 2014-09-06 17:29:08

1
string input = @"take everything 1 foo take everything 2 foo take everything 3 
take everything 4"; 

var result = Regex.Matches(input, @"(.+?)((?>foo)|(?>$))", RegexOptions.Multiline) 
        .Cast<Match>() 
        .Select(m => m.Groups[1].Value.Trim()) 
        .ToList(); 

enter image description here

相關問題