3

I'm trying to find match between a string and pattern using Regex.IsMatch(). I framed the regex and tested it using regex101.com it works fine. Now problem is that Regex.IsMatch(filename, curSetting.RegExMatch.ToString()); returns true curSetting.RegExMatch.IsMatch(filename)) returns false for same filename. Can someone explain how does this differ and what is the difference between them?

RegExMatch is my regex member of curSetting object. Test data in my case is Pattern is

Gen(?!.*(?:erallog))(?<SerialNo>.+?)-(?<Year>(?:\d{2}))(?<Month>\d{2})(?<Day>\d{‌2})(?<Other>.*?\.log‌)

The string is 1_GeneralLog1370013-170403.log.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Please share the full relevant code. What is the `curSetting.RegExMatch` pattern? What is `filename` value? – Wiktor Stribiżew May 02 '17 at 10:13
  • It would be helpfull when you are posting the pattern and the text you are searching in. And maybe this will help you [Regular Expression working in regex tester, but not in c#](http://stackoverflow.com/questions/24687028/regular-expression-working-in-regex-tester-but-not-in-c-sharp) – Mighty Badaboom May 02 '17 at 10:13
  • What type is `RegExMatch`? Never heard of it. –  May 02 '17 at 10:15
  • `RegExMatch` is my regex member of `curSetting` object. Test data in my case is Pattern is `Gen(?!.*(?:erallog))(?.+?)-(?(?:\d{2}))(?\d{2})(?\d{2})(?.*?\.log)` string is `1_GeneralLog1370013-170403.log` – Sudhir Somu May 02 '17 at 10:49
  • [I get *true* for both cases](http://ideone.com/ghbYHD). What are the flags your `curSetting.RegExMatch` is compiled with? I guess you used `Regex.IgnoreCase`. So, what do you want now? – Wiktor Stribiżew May 02 '17 at 11:33
  • So, did my answer help? – Wiktor Stribiżew May 02 '17 at 18:46

1 Answers1

2

It is clear that your curSetting.RegExMatch is compiled with a RegexOptions.IgnoreCase flag: the (?!.*(?:erallog)) is handled case-insensitively and matches the eralLog in your 1_GeneralLog1370013-170403.log input string, so the negative lookahead pattern finds a match and fails the overall match.

So, there are 2 ways out (depending on what you need):

  • Either remove the RegexOptions.IgnoreCase from the regex object initialization or
  • Add the case-insensitive inline option (?i) into the pattern:

    (?i)Gen(?!.*(?:erallog))(?<SerialNo>.+?)-(?<Year>(?:\d{2}))(?<Mo‌nth>\d{2})(?<Day>\d{2})(?<Other>.*?\.log)

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563