tags:

views:

467

answers:

2

This is one of the most used Regex functions

Regex.IsMatch("Test text for regex test.", "(test)",
RegexOptions.IgnoreCase | RegexOptions.Multiline);

Can you explain how Regex.IsMatch method works ? I mean how it handles bitwise OR RegexOptions parameters ? How it defines method parameters ?

Thanks for replies !

+6  A: 

RegexOptions is an enumeration with the [Flags] attribute applied to it. This allows bitwise operations to be applied to the various values.

You can also do something similar:

[Flags]
enum MyOptions {
   UpperCase = 1,
   Reverse   = 2,
   Trim      = 4
}

public static void DoTransform(MyOptions options) {
    if ((options & MyOptions.UpperCase) == MyOptions.UpperCase) {
        /* Do Upper case transform */
    }
    if ((options & MyOptions.Reverse) == MyOptions.Reverse) {
        /* Do Reverse transform */
    }
    /* etc, ... */
}

DoTransform(MyOptions.UpperCase | MyOptions.Reverse);

I've just done a bit more digging based on Frank's comment and he is correct that with or without the [Flags] attribute, the code above will compile and run.

There have been other comments in regard to what the [Flags] attribute does not do but other than "it affects the ToString() result" no one seems to know or wants to explain what it does do. In code I write, I adorn enumerations that I intend to use as bitfields with the [Flags] attribute, so in that case it is at least somewhat self-documenting. Otherwise, I'm at a loss.

Sean Bright
The information about Flags is incorrect. It will happily compile without the Flags attribute. However, looking at the msdn documentation, using the Flags attribute affects the ToString() output. Write a Console.WriteLine(options) and check out the difference by leaving or removing the attribute.
flq
Looks like you're right, I've updated my sample.
Sean Bright
By the way, VB will do nothing of that sort. This would actually be really stupid because sometimes it's meaningful to create aliases for flag names, that obviousl contain the same value. So that explanation at least is off.
Konrad Rudolph
Lots of nay-saying and very little in the way of useful information. Any idea what the point of the Flags attribute does, then? I think we have covered what it DOESN'T do sufficiently.
Sean Bright
A: 

RegexOptions is an enumeration, meaning that internally, it's represented as an integer. The values of it look something like this:

// note the powers of 2
enum RegexOptions {
    IgnoreCase = 1,      MultiLine = 2,
    SomeOtherOption = 4, YetAnotherThing = 8 }

The values are designed so that if you express them in binary, each one has a single bit on.

Because of this, if you take the bitwise OR of two values and end up with a result, you can figure out if one of the values is set (e.g. IgnoreCase) by evaluating (result AND IgnoreCase).

mquander