Link to home
Start Free TrialLog in
Avatar of no158
no158

asked on

how to ignore strings starting with numbers

lets say i have a few strings

Welcome
test
123bat
ball456

and I have a foreach looking at all the strings
how can i quickly test if the first char in the string is a number

output should look like

Welcome
test
ball456
Avatar of Dirk Haest
Dirk Haest
Flag of Belgium image

string strToTest = "123";
Regex reNum = new Regex(@"^\d+$");
(or regex(@"^\d{5}$");
bool isNumeric = reNum.Match(strToTest).Success

http://www.codeproject.com/KB/cs/csharp-isnumeric.aspx
......

int a;

if(Int32.TryParse(yourstring.SubString(0,1), out a) == true)
    MessageBox.Show("Yes, this is start with number");

....

Avatar of no158
no158

ASKER

Tried using the regular expression first with this as data

123first test
second123 test
this123third test
123

all of them went through, as if there was no test

Secondly i tried the Int32.TryParse but it seems that my string wont allow substrings


here is what i'm working with


                            foreach (string s in myString)
                            {
                                if (!(startString.Contains(s)))
                                {
                                    Regex reNum = new Regex(@"^\d{5}$");
                                    bool isNumeric = reNum.Match(s).Success;
                                    if (!isNumeric)
                                    {
                                        myString[count] = s;
                                        list = new KeyValueList(myString[count], lineTemp, index);
                                        myList.Add(list);
                                        count++;
                                    }
                                }
                                index++;
                            }

Open in new window

Try it with 1 instead of 5
Regex reNum = new Regex(@"^\d{1}$");
Avatar of no158

ASKER

Didn't work either.

On second thought, it would be better if it would just not accept any string with a digit in it.
If this makes it easier.

So all these would fail the test.

123first
second123
this123third
123
ASKER CERTIFIED SOLUTION
Avatar of Colemss
Colemss
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>> On second thought, it would be better if it would just not accept any string with a digit in it.
If this makes it easier.

Does the user needs to input this in a textbox ? Then I would also accept only numeric values, ...
Avatar of no158

ASKER

internal static bool IsNumeric(string numberString)
{
    foreach (char c in numberString)
   {
        if (!char.IsNumber(c))
             return false;
   }
   return true;
}

worked perfect for what I was doing. Only thing was I used IsDitgit.