Hi All,
So much Helping Deniweb in during interuption in my code.
Again for small query I hope it will give enjoyful result to Me.

I want reguler expression which having "Only Numeric-Positive-Non Zero-and Must Non Empty" value.
I have all ready Done expression "^[1-9]+[0-9]*$" giving result for Positive-Non Zero Value"
But for Empty-null value it's not work.

Guys, wait for your reply.

Thanks.
Mr.Dhimmar.

Recommended Answers

All 4 Replies

If the string is empty then the match will fail anyway since you require 1 or more of the first character.
You will possibly throw an exception if you try a regex search on a null string so your better to check for null first, and if not null, then check for match. Something like:

string pattern = "^[1-9]+[0-9]*$";
    string toSearch = null;
    if (!string.IsNullOrEmpty(toSearch) && Regex.IsMatch(toSearch, pattern))
    {
        //string is valid
    }

The && operator is a conditional check (also called ShortChaining) which means that if the first part equates to false the second part is not checked. This ensures that if your string is empty or null the second part is not checked so you wont get an exception for trying to check a null string :)

Thanks for Reply.
Not Found Any Class Like Regex .Is there any namespace required to use Regex?

The following code, using your expression, reports Match=False for test=string.Empty; .

string rx = "^[1-9]+[0-9]*";
Regex reg = new Regex(rx);
string test = string.Empty;
MessageBox.Show(string.Format("IsMatch={0}", reg.IsMatch(test)));

However, for test = null; an error is generated, as the parameter to IsMatch can not be null.
Perhaps this is the problem you are having with your test?
If so then check the string is not null before testing the regex.

string test = string.Empty;
if(string.IsNullOrEmpty(test))
{
    MessageBox.Show("No Value");
}
else
{
    string rx = "^[1-9]+[0-9]*";
    Regex reg = new Regex(rx);
    MessageBox.Show(string.Format("IsMatch={0}", reg.IsMatch(test)));
}

Just Add to NameSpace using System.Text.RegularExpressions;
Thanks it's working as requirement.

Thanks...Ryshad.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.