Click here to Skip to main content
15,909,822 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hello..........

I am beginner in c# programming, want to know How does this code executes. Kindly describe in detail.

!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+")

Soon reply will be appreciated.....!!!!

Thanks....
Posted
Comments
PIEBALDconsult 24-Jan-13 1:32am    
It executes very poorly I suspect. I hope your task is to improve it, because it's inefficient, but can easily be improved.

I assume it's in a KeyPress or similar event handler for a TextBox or similar control. If so, then it is checking whether or not the key is a digit, but it's just very very bad; there's really nothing good about it. Words can't convey...

Aaanywaaay... Each time a key is pressed, that character is turned into a string (this is very bad) and a Regex (look up Regular Expressions) object is instantiated to compile the provided expression -- which will search the string for a series of one or more digits anywhere in the string. The result ("yes it matches" or "no it doesn't match") will then be negated. Then the Regex and the string are thrown out.

The whole thing should be thrown out, but let's look at improving it first:

If we take a character and make a string of it, the string will contain only one character, it will never contain more than one -- so remove the extraneous +.

Likewise, the digit won't be "somewhere in the string", it'll occupy the whole string -- so you could add ^ at the start and $ at the end. I doubt this will make any difference one way or the other.

You could also change the Regex to say "is not a digit" rather "is a digit" to avoid the negation later.

Don't keep instantiating and throwing out the Regex; make one and keep using it. You can do this by making a private (possibly static and possibly readonly) field and instantiate it in the constructor of your Form (I assume it's a Form).

So now we haveprivate readonly System.Text.RegularExpressions.Regex IsNotDigit ;

IsNotDigit = new System.Text.RegularExpressions.Regex ( "^\\D$" ) ; // In the constructor

IsNotDigit.IsMatch ( e.KeyChar.ToString() ) // in the event

but we still have that nasty and needless ToString()All you need is !System.Char.IsDigit ( e.KeyChar ) .

1 solution

1. Is Google down ! Last I checked few minutes back, it was working !

2. MSDN is also on and you have to just press "F1!. It will bring http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.ismatch.aspx[^]

2. Is it just me or does this mail sound like Project Manager sending mail to developer.

Milind
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900