Canavar
Canavar

Reputation: 48088

Bitwise OR Combination

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 !

Upvotes: 2

Views: 2646

Answers (2)

Sean Bright
Sean Bright

Reputation: 120644

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.

Upvotes: 7

mqp
mqp

Reputation: 71945

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).

Upvotes: 1

Related Questions