除非它看到食物,否则取一切

时间:2014-09-06 17:17:06

标签: c# javascript regex

学习正则表达式。

除非看到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

  3. 请赐教。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

你可以试试下面的正则表达式,

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

DEMO

  • (?<=foo|^)看看foo或该行的开头。
  • (.*?)匹配字符串foo或行尾的所有内容。

答案 2 :(得分: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