Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why RegexOptions are compiled to RegexOptions.None in MSIL?

Tags:

c#

.net

regex

il

This code

  Regex regex = new Regex("blah", RegexOptions.Singleline & RegexOptions.IgnoreCase);

after compilation looks like this in ILSpy:

  Regex regex = new Regex("blah", RegexOptions.None);

Why does it happen and can it be the reason of regex not matching in .Net 3.5? On 4.5 it works.

like image 259
Anatoly Sazanov Avatar asked Oct 30 '15 15:10

Anatoly Sazanov


People also ask

What is RegexOptions compiled?

RegexOptions. Compiled instructs the regular expression engine to compile the regular expression expression into IL using lightweight code generation (LCG). This compilation happens during the construction of the object and heavily slows it down. In turn, matches using the regular expression are faster.

What are regex options?

Multiline mode. The RegexOptions. Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines.


1 Answers

RegexOptions.Singleline & RegexOptions.IgnoreCase

is a bitwise AND, and resolves to 0 (i.e. RegexOptions.None).

The RegexOptions enum looks like this:

[Flags]
public enum RegexOptions
{
    None = 0,
    IgnoreCase = 1,
    Multiline = 2,
    ExplicitCapture = 4,
    Compiled = 8,
    Singleline = 16,
    IgnorePatternWhitespace = 32,
    RightToLeft = 64,
    ECMAScript = 256,
    CultureInvariant = 512,
}

So, in binary, we have:

RegexOptions.SingleLine == 10000 
RegexOptions.IngoreCase == 00001

When applying a bitwise AND, we get :

    10000 
AND 00001
    -----
    00000

Replace with

RegexOptions.Singleline | RegexOptions.IgnoreCase

which gives:

    10000 
 OR 00001
    -----
    10001

That ILSpy will decompile in:

Regex regex = new Regex("blah", RegexOptions.Singleline | RegexOptions.IgnoreCase);

But I don't know what "works" in .Net 4.5. I just compiled your code, and ILSpy also outputs:

Regex regex = new Regex("blah", RegexOptions.None);

as intended.

like image 179
xlecoustillier Avatar answered Nov 03 '22 00:11

xlecoustillier