学习Regex。
我想匹配所有的东西,除非它看到foo。
输入:
take everything 1 foo take everything 2 foo take everything 3
take everything 4Expect:
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请指点我。
发布于 2014-09-06 17:24:38
将单词边界\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发布于 2014-09-06 17:24:29
你可以试试下面的正则表达式,
(?<=foo|^)(.*?)(?=foo|$)演示
(?<=foo|^)查找foo或行的开头。(.*?)匹配到字符串foo或行尾的所有内容。发布于 2014-09-06 17:28:30
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();

https://stackoverflow.com/questions/25702805
复制相似问题