Reputation: 3693
I try to find string that doesn't contains the same substring. This is my code:
var regex = new Regex(@"aaa(?!.*aaa).*aaa");
var str1 = @"aaa aaa aaa";
var match = regex.Match(str1); // no
var str1 = @"aaa bbb aaa";
var match = regex.Match(str1); // yes
But this code doesn't work... What I do wrong?
Thanks!
Upvotes: 0
Views: 4051
Reputation: 6136
Im going to take a stab in the dark here and guess that you're trying to do this.
i.e.
`\b(\w+)\s+(?!\1\b)`
Matches a word \b(\w+)
Followed by whitespace \s+
Followed by a negative look-ahead for a back reference to the previously matched word. (?!\1\b)
[Test]
public void RegexTest()
{
var regex = new Regex(@"\b(\w+)\s+(?!\1\b)");
var str1 = @"aaa aaa aaa";
Assert.IsFalse(regex.IsMatch(str1)); // no
var str2 = @"aaa bbb aaa";
Assert.IsTrue(regex.IsMatch(str2)); // yes
}
Upvotes: 0
Reputation: 33908
You want an expression like this:
aaa(?:(?!aaa).)*aaa
(?:(?!aaa).)*
matches strings that do not contain aaa
(in whole or part).
You could also write it like this:
aaa(?:[^a]+|a(?!aa))*aaa
Upvotes: 7