开发者

Matching Zero Using Regular expression

How to do the following using Regex

String Str="11111111";
if(Str.Contains("0"))
         MessageBox.Show("Not matching");
else
         MessageBox.Show("Matching");

Is this Pattern correct Regex rx=new Regex("0*"); ?

Mathc mh=rx.Match(Str);

if(mh.Success==false)
         MessageBox.Show("Not matching");
else
         MessageBox.Show("Matching");

But its not working. My string Str does not have 0 but its showing mh.Success=true

Please help 开发者_运维百科me


The asterisk (*) means 0 or more occurences, what you want is just to find a single occurence anywhere, so simply "0" would do, i.e:

Regex ex = new Regex("0");


The regular expression 0* refers to zero or more 0s. That's the reason the match is a success. As Aviad P. says, just the expression 0 would do. Alternatively, you could use an expression such as ^[^0]*$ as a test expression that must match the entire string. Of course, there's no reason to use regex here when a simple string.Containsdoes the job.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜