Regex negative character set

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi All,

It might be because its the end of a long week, but I can't figure out the
correct way to write a regular expression to find all matches except a
specified string.

For example, take the following 3 lines:
This is OK
This is Not OK
Again This is OK

I want to find the first and last line, and not the "This is Not OK" line.

Thanks,
PAGates
 
pagates said:
It might be because its the end of a long week, but I can't figure out the
correct way to write a regular expression to find all matches except a
specified string.

I don't know how to write such a regex either, but I'd do it this way:

Regex r = new Regex("This is Not OK");

if (r.IsMatch(line) == false) { // if it doesn't match "This is Not Ok"...
// ... it's got to be Ok.
}

hth,
Max
 
: It might be because its the end of a long week, but I can't figure out
: the correct way to write a regular expression to find all matches
: except a specified string.
:
: For example, take the following 3 lines:
: This is OK
: This is Not OK
: Again This is OK
:
: I want to find the first and last line, and not the "This is Not OK"
: line.

That's actually a little tricky. If you don't believe me, try to
construct a regular expression that doesn't contain the string "ab".
Then do the same for "abc".

Why not use the much simpler approach of looking for match failures?

static void Main(string[] args)
{
string[] inputs = new string[] {
"This is OK",
"This is Not OK",
"Again This is OK"
};

Regex dontwant = new Regex(@"^This is Not OK$");

foreach (string input in inputs)
if (!dontwant.Match(input).Success)
Console.WriteLine(input);
}

If we had a better idea of the problem you're trying to solve, we could
probably give you more useful advice.

Greg
 
Hi Greg,

The problem I'm to solve is actually writing a macro in the IDE to find
(next and previous) #region keywords. I have no problem doing that, but the
unfortunate side effect is that when they are found, they are expanded.
Therefore, I was looking for a quick-n-dirty way to skip the "Component
Designer generated code" region.

The IDE Macro find allows searching using Regular Expressions, so I thought
I could do so here. More of a curiousity than something I want to spend any
significant time on.

Thanks,
PAGates
 
Back
Top