学习正则表达式。
除非看到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`
尝试:
([^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
(.*(?!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 :(得分: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)
答案 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();