Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Ok this is going to be a weird question not gonna lie. I have a device and when i hit a button it sends a string like "135,125,154,458". I use Split and Trim and get the numbers which I need and draw a rectangle using the numbers. However when i hit multiple buttons at the same time it sends weird characters therefore it crashes. I need to check the string to make sure it contains only "," and "numbers" so that if there is anything other than those it won't pass it. Is there a way to do it?
private void InputBox_TextChanged(object sender, EventArgs e)
        {
            if (InputBox.Text.StartsWith("π") == false)//Clear the box if the message does not start with π
            {
                InputBox.Text = "";
            }
            if ((InputBox.Text.StartsWith("π") == true) && (InputBox.Text.EndsWith("}") == true))// only process if the message starts with π and ends with }
            {
                string Message = InputBox.Text;
                InputBox.Text = "";// Clear the box when done. 
                if (Message.StartsWith("πImageBox_Coordinates{") == true) ///Coordinates
                {
                    Message = Message.Substring(22);
                    Message = Message.TrimEnd('}');
                    string[] MessageSplit = Message.Split(new char[] { ',' });
                    for (int i = 0; i < MessageSplit.Count(); i++)
                    {
                        buttcorrs[i] = Convert.ToInt16(MessageSplit[i]);


it crasher at the last line where i convert it. It works great when i hit it one by one but I also need multiple hits so if anyone has an idea would appreciate it.

Thank you,
Posted

I had to play around with it quite a bit to get it to work as I am not that familiar with regular expressions, but here's what I believe will work best.

Use the System.Text.RegularExpressions library.

Within it is a class called RegEx.

Create a new RegEx class like:

VB
Regex myRegEx = new RegEx("^\d+((,\d+)*)$")

(that was my clumsy conversion from VB)...that won't work in C#. In C#, it should be:
C#
RegEx myRegEx = new RegEx(@"^\d+((,\d+)*)$");


Then, pass the string you want to match in using myRegEx.IsMatch(stringToTest).

If it is true, then it should only have letters numbers and commas. If false, it has something else.

I tested the following and got the following results:
"483,3929,2020" True
"3939,2902s,1292" False
"A394" False
"394,394" True
"394,394s" False
"394" True

So, I'll try to explain what it's doing in case you aren't familiar with regular expressions.

The caret (^) tells it to start at the beginning. "\d+" tells it to look for one or more digits. So the first block "^d\+" says "start at the beginning and check for as many digits as there are. Then it moves on to the next block ("((,\d+)*)$").

The (...)$ says whatever is inside of it has to be at end of the string for this to match. And it will start whenever the previous test fails (so when there isn't a digit).

The (,\d+) says when there isn't a digit check to see if it's a comma. If it isn't, it will fail. If it is, it will then check for digits again (as many as there are). The (...)* says find as many of those as possible. So, it will look first for digits. Then, a comma and more digits and it will repeat looking for a comma and more digits until it gets to the end. If it doesn't end with that pattern, it will fail.
 
Share this answer
 
v3
Comments
Kythen 24-May-10 23:53pm    
A small point of clarification for the benefit of the original poster: Make sure to call this myRegEx.IsMatch() with Message *after* doing the call to TrimEnd('}') as our regular expressions would fail if the ending '}' was still included.
TolgaCiftci 25-May-10 9:07am    
I don't know if my earlier comment went through but I can't see it posted so if this is a duplicate accept my apologies. When I try your code it is giving me unrecognized escape sequence error for "d"s on the expression. Any ideas?
William Winner 25-May-10 11:42am    
What does your code look like? I ran it exactly like I said and I wasn't getting any errors.
Kythen 25-May-10 11:54am    
The regex string is just a normal string, so you have to escape special characters like the backslash with an additional backslash character or turn it into a verbatim string by putting a @ character before the first double-quote character.
William Winner 25-May-10 12:03pm    
thanks Kythen...clumsy conversion from VB to C# on my part.
Right after you do the Message.TrimEnd('}') call, use a regular expression to validate the message.

If your message should always look like 123,456,678 with no spaces use the regular expression:
^\d+(,\d+)*$


If spaces are allowed between numbers, use this regular expression instead:
^\d+(,\s*\d+)*$


[Edit: Fixed regex expressions per William Winner's bug catch]
 
Share this answer
 
v4
Comments
William Winner 24-May-10 17:09pm    
that won't work in all situations. for instance "A394 will match. Also, "394,394S" matches. You have to exclude all other characters as well...
William Winner 24-May-10 17:31pm    
Reason for my vote of 2
close, but misses the mark.
Kythen 24-May-10 23:42pm    
You're absolutely correct. I hadn't payed close attention and missed including the ^ and $. The answer has been edited to fix this.
William Winner 25-May-10 11:40am    
I swapped my 2 vote for a 5 vote with the correction
on a side note, if the first if block is true, you can simply return and then none of the other lines will run...ie
C#
if (InputBox.Text.StartsWith("π") == false)//Clear the box if the message does not start with π
{
     InputBox.Text = "";
     return;
}


If you check for a condition to be false, you should never then have to check for a condition to be true as you do...

C#
if (InputBox.Text.StartsWith("π") == false)
...
if ((InputBox.Text.StartsWith("π") == true)


you should either return and then you don't need to check it, or use an else if statement ie.

C#
if (InputBox.Text.StartsWith("π") == false)//Clear the box if the message does not start with π
{
    InputBox.Text = "";
}else if (InputBox.Text.EndsWith("}"))


(you also don't need to check if something "== true". That's just adding an extra step for the compiler. String.EndsWith returns true or false.)

I also don't understand what you mean when you say if you hit multiple buttons. You can't possibly hit them at the same time, and even if you programattically hit them one after the other, the second button click event wouldn't fire until the first one had finished...for instance if you did:

C#
Button1.PerformClick();
Button2.PerformClick();


Button2's click event wouldn't fire until Button1's had completely finished unless you're opening them on different threads which if that was the case, you would need to do some synchronization.
 
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