regex: NOT operation

  • Thread starter Thread starter keber
  • Start date Start date
K

keber

Hi folks,

With the Regular Expressions is there a way to specify a matching pattern
that will fail if the text contains a quote. I'm sure it's painfully easy.

Cheers
 
Hi Keber,
With the Regular Expressions is there a way to specify a matching pattern
that will fail if the text contains a quote. I'm sure it's painfully easy.

I think the circumflex character ^ is the closes you can get for a NOT
operation in regular expressions. See the Regular Expression Language
Elements / Character Classes topic in the .NET SDK documentation (reference
section) for details.

But instead of fiddling with the circumflex thing, why not simply look for a
quote, and then if one is found, decide what should be done? That is
probably easier. For example in C#:

Regex regex = new Regex("\"");
string input1 = "This is some data";
string input2 = "This another string of da\"ta.";
if (regex.IsMatch(input1))
{
Console.WriteLine("Input1 matches the regex.");
}
if (regex.IsMatch(input2))
{
Console.WriteLine("Input2 matches the regex.");
}

That would print "Input2 matches the regex." i.e. match the second string
only. If you want to match both the double quote and the single quote
characters, you could use a Regex like this:

Regex regex = new Regex("[\"']");

However, if you are only looking for either one in your input string, I
wouldn't use regular expressions at all. Instead, it is faster and easier to
just use the IndexOf method of the String class, like this:

if (input2.IndexOf("\"") >= 0)
{
Console.WriteLine("Input2 contains a quote char.");
// do some real work here
}

Hope this helps.

--
Regards,

Mr. Jani Järvinen
C# MVP
Helsinki, Finland
(e-mail address removed)
http://www.saunalahti.fi/janij/
 
Back
Top