简体   繁体   中英

REGEX matches in tester but not C#

I have a line from a file: ; STRING WBSALT1() ; STRING WBSALT1()

and code

if (!Regex.IsMatch(line, @"\s*(;)(.*)", RegexOptions.IgnoreCase))
   {
       //do
       //stuff
   }

For some reason the REGEX isn't matching that line in the file. I ran it through a tester and it catches it just fine. Does anyone know what else could be causing the problem?

it will, however, match this (in code, not in a regex tester)

if (Regex.IsMatch(line, @"\s*(string)\s*(.*\()\s*(\d*)\)\s*;?(.*)", RegexOptions.IgnoreCase))

which really doesn't make any sense to me. I have no other issues with the thousands of other lines in the file that look similar. Any ideas?


EDIT : Okay so I didn't place it in the question because I didn't think it necessary. Apparently it is:

My ACTUAL if statement looks like this:

if (!Regex.IsMatch(line, @"\s*;.*") || !Regex.IsMatch(line, @"\s*(origin)\s*(.*)", RegexOptions.IgnoreCase))

Now, when I take off the || statement it works properly. Why it is doing this I do not understand. Maybe someone has some insight into this?

Tested in my environment and works as expected.

        string line = "; STRING WBSALT1()";

        if (!Regex.IsMatch(line, @"\s*(;)(.*)", RegexOptions.IgnoreCase))
           {
               //do
               //stuff
           }

Wondering if maybe you did not intend for the "!" to be part of the condition

 if(! ...

Regards,

Just to add you don't need IgnoreCase set here if you're using .* and you can lose the capture groups. You may also want to add beginning ^ and ending $ line anchors.

Tested on Ideone

string line = "; STRING WBSALT1()";
if (!Regex.IsMatch(line, @"^\s*;.*$")) {
   // do something
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM