简体   繁体   English

REGEX在测试器中匹配,但在C#中不匹配

[英]REGEX matches in tester but not C#

I have a line from a file: ; STRING WBSALT1() 我从文件中的行: ; 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. 由于某种原因,REGEX与文件中的该行不匹配。 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: 我的ACTUAL if语句如下:

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. 仅添加即可,如果您使用.* ,则无需在此处设置IgnoreCase并且可能会丢失捕获组。 You may also want to add beginning ^ and ending $ line anchors. 您可能还想添加开始^和结束$行锚。

Tested on Ideone Ideone测试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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