Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex 'Ignore Case' option doesn't work when the 'Compiled' option is specified

Tags:

c#

regex

I have the following very simple regex, which matches HTML tags in a string. I have the case insensitive option set, so that capitalisation of the tags doesn't matter. However, when the 'compiled' option is set, then the 'IgnoreCase' option seems to be ignored.

Sample code:

string text = "<SPAN>blah</SPAN><span>blah</span>";
Regex expr1 = new Regex("</*span>", RegexOptions.IgnoreCase);
Regex expr2 = new Regex("</*span>", RegexOptions.IgnoreCase & RegexOptions.Compiled);

MatchCollection result1 = expr1 .Matches(text); 
//gives 4 matches- <SPAN>,</SPAN>,<span> & </span>
MatchCollection result2 = expr2 .Matches(text);
//only gives 2 matches- <span> & </span>

Has anybody got an idea what is going on here?

like image 597
John Avatar asked May 10 '12 13:05

John


People also ask

How do you handle case sensitive in regex?

In Java, by default, the regular expression (regex) matching is case sensitive. To enable the regex case insensitive matching, add (?) prefix or enable the case insensitive flag directly in the Pattern. compile() .

Does case matter in regex?

Discussion. Currently, REGEXP is not case sensitive, either.

Is regex search case sensitive?

Regex search is case insensitive · Discussion #10708 · community/community · GitHub.


1 Answers

You are using a bitwise AND for your flags, you should be using a bitwise OR.

This bit:

RegexOptions.IgnoreCase & RegexOptions.Compiled

Should be:

RegexOptions.IgnoreCase | RegexOptions.Compiled

Here is a good article on how flags and enumerations work in respect to C#.

like image 193
vcsjones Avatar answered Oct 02 '22 06:10

vcsjones